Skip to content

Commit 1b55f52

Browse files
Copilotm-aciek
andcommitted
Remove date/date comparison warnings as inheritance blocking makes them redundant
Co-authored-by: m-aciek <9288014+m-aciek@users.noreply.github.com>
1 parent cb83a2a commit 1b55f52

2 files changed

Lines changed: 4 additions & 16 deletions

File tree

mypy/checkexpr.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3886,11 +3886,6 @@ def has_unsafe_subtype_relationship(self, left: Type, right: Type) -> bool:
38863886
38873887
Returns True if they are instances with a nominal subclass relationship
38883888
that is known to be unsafe (e.g., datetime and date).
3889-
3890-
This also flags comparisons between two values of the supertype (e.g., date vs date)
3891-
because at runtime, one could be an instance of the unsafe subclass (e.g., datetime).
3892-
While conservative, this is necessary to catch LSP violations where the subclass
3893-
has incompatible comparison operators.
38943889
"""
38953890
from mypy.subtypes import UNSAFE_SUBTYPING_PAIRS
38963891

@@ -3909,13 +3904,6 @@ def has_unsafe_subtype_relationship(self, left: Type, right: Type) -> bool:
39093904
if ((left_name == subclass and right_name == superclass)
39103905
or (left_name == superclass and right_name == subclass)):
39113906
return True
3912-
3913-
# Also flag when both types are the supertype, as one could be the subclass at runtime.
3914-
# Example: comparing 'date' vs 'date' is unsafe because one could be a 'datetime'.
3915-
# This is conservative but necessary due to Python's subtyping allowing datetime
3916-
# instances to be used wherever date is expected, despite incompatible comparison.
3917-
if left_name == superclass and right_name == superclass:
3918-
return True
39193907

39203908
return False
39213909

test-data/unit/check-unsafe-subtype.test

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,8 @@ d2: date
119119
if dt1 < dt2:
120120
pass
121121

122-
# date vs date is unsafe because one could be a datetime at runtime
123-
if d1 < d2: # E: Unsafe comparison between "date" and "date"; runtime comparison may raise TypeError
122+
# date vs date is now OK since inheritance blocking prevents datetime from being passed as date
123+
if d1 < d2:
124124
pass
125125
[builtins fixtures/classmethod.pyi]
126126
[file datetime.pyi]
@@ -207,8 +207,8 @@ class datetime(date):
207207
from datetime import date, datetime
208208

209209
def compare_dates(d1: date, d2: date) -> bool:
210-
# This is flagged because one of the dates could be a datetime at runtime
211-
return d1 < d2 # E: Unsafe comparison between "date" and "date"; runtime comparison may raise TypeError
210+
# With inheritance blocking, this is now safe - datetime cannot be passed here
211+
return d1 < d2
212212

213213
# Example usage that would fail at runtime:
214214
dt = datetime.now()

0 commit comments

Comments
 (0)