Hello,
I’d like to discuss adding an optional mypy feature that rejects unsafe subtype-based usage between date and datetime.
Currently the following code passes type checking but raises TypeError at runtime:
from datetime import date, datetime
if datetime.now() < date.today():
print("that's a surprise!")
This happens because datetime inherits from date, but does not fully behave as a substitutable subtype. In particular, ordering comparisons between date and datetime raise TypeError.
This mismatch has been a long-standing source of subtle runtime errors that type checkers currently do not catch.
I’ve opened a prototype implementation in mypy:
One design consideration is that this is not merely a check for comparisons that would fail at runtime. In practice, the implementation works by restricting use of the datetime <: date subtype relationship itself. Detecting only comparison operations would be incomplete and would miss many cases where the relationship has already been relied upon by the type checker.
This proposal assumes no changes to typeshed and preserves current runtime inheritance relationships.
I would appreciate feedback on the following questions:
- a new error code (enabled when feature is on)
- a dedicated flag
I also briefly considered a more general mechanism for handling known problematic subtype relationships (for example bool/int or str/Iterable[str]; suggested by Jukka). However, similar discussions already exist for those cases, and I think it is easier to evaluate the date/datetime case on its own merits before considering a broader framework.
I would also welcome any feedback on the PR, particularly on the design and scope.
- safe-datetime
- strict-date
- other (comment)
Chronological references
- Mar 12, 2015 – first stubs for
datetimeappear intypeshed - Sep 15, 2015 – todo added for
datetimeclass- “is actually subclass of date, but __le__, __lt__, __ge__, __gt__ don’t work with date.”
- Improve several stubs. (math, _random, time, etc.) · python/typeshed@dd042b3 · GitHub
- Sep 30, 2015 – file moved, todo updated
- “Is a subclass of date, but this would make some types incompatible.”
- add (overwrite with) mypy stubs, if available · python/typeshed@337abed · GitHub
- Sep 26, 2018
typeshedissue thatdatetimeanddateare incompatible- PR following – Make 'datetime' a subclass of 'date'. by mvaled · Pull Request #2488 · python/typeshed · GitHub
- Mar 3, 2020 – Glyph’s issue in
typeshed - Jun 17, 2020 – Glyph’s issue in
mypy - Dec 4, 2020 – tomasachan’s issue in
pyright - Dec 6, 2020 – tomasachan’s issue in
typeshed - May 19, 2022 – Glyph’s workaround library
- Nov 10, 2023 – new datetime library that has types without inheritance
- Feb 11, 2025 – mttbernardini’s workaround
- Jun 9, 2025 – issue in
ty