Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

datetimes and dates are not substitutable but mypy thinks they are #9015

glyph opened this issue Jun 17, 2020 · 3 comments

datetimes and dates are not substitutable but mypy thinks they are #9015

glyph opened this issue Jun 17, 2020 · 3 comments


Copy link

glyph commented Jun 17, 2020

Note: if you are reporting a wrong signature of a function or a class in
the standard library, then the typeshed tracker is better suited
for this report:

I tried that first ;-) python/typeshed#3805

Please provide more information to help us understand the issue:

  • Are you reporting a bug, or opening a feature request?

This is a bug in the system overall but probably a feature request in mypy itself.

  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from datetime import date, datetime

if <
    print("that's a surprise!")
  • What is the actual behavior/output?

No error!

  • What is the behavior/output you expect?

A warning, since at runtime I get TypeError: can't compare datetime.datetime to

  • What are the versions of mypy and Python you are using?

0.770, 3.8.2

  • Do you see the same issue after installing mypy from Git master?


  • What are the mypy flags you are using? (For example --strict-optional)
Copy link

JukkaL commented Jun 19, 2020

LSP violations are generally tricky. Some of them are fairly benign and rarely cause issues, but others can be painful.

As typeshed includes the subclass relationship present in the implementation, current mypy behavior is arguably "correct". However, I can imagine a way to deal with this in mypy: introduce optional subtype checks that would complain about code that relies on subtyping relationships that are not safe, such as datetime vs date. Mypy would maintain a set of known unsafe subtyping relationships, including cases where a class is a subclass of another class but shouldn't be treated as a subtype. This could also be used for things like warning about str used as Iterable[str].

Copy link

m-aciek commented Jul 5, 2023

Sharing a workaround typing library created by @glyph: Found on StackOverflow.

Copy link

glyph commented Jul 7, 2023

Thanks @m-aciek, I forgot to link it directly from here :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet

No branches or pull requests

3 participants