Skip to content

Commit 4616fa2

Browse files
committed
Believe arbitrary __new__ return types
Fixes #1020 (comment) Surprisingly popular comment on a closed issue. We still issue the warning, but we do trust the return type instead of overruling it. Maybe fixes #16012
1 parent 2a6d9cb commit 4616fa2

File tree

3 files changed

+5
-5
lines changed

3 files changed

+5
-5
lines changed

mypy/typeops.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,9 +197,9 @@ def class_callable(
197197
# by accident. Like `Hashable` is a subtype of `object`. See #11799
198198
and isinstance(default_ret_type, Instance)
199199
and not default_ret_type.type.is_protocol
200-
# Only use the declared return type from __new__ or declared self in __init__
200+
# Only use the declared return type from declared self in __init__
201201
# if it is actually returning a subtype of what we would return otherwise.
202-
and is_subtype(explicit_type, default_ret_type, ignore_type_params=True)
202+
and (is_new or is_subtype(explicit_type, default_ret_type, ignore_type_params=True))
203203
):
204204
ret_type: Type = explicit_type
205205
else:

test-data/unit/check-classes.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6883,7 +6883,7 @@ class A:
68836883
def __new__(cls) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")
68846884
pass
68856885

6886-
reveal_type(A()) # N: Revealed type is "__main__.A"
6886+
reveal_type(A()) # N: Revealed type is "builtins.int"
68876887

68886888
[case testNewReturnType4]
68896889
from typing import TypeVar, Type
@@ -6960,7 +6960,7 @@ class A:
69606960
class B(A):
69616961
pass
69626962

6963-
reveal_type(B()) # N: Revealed type is "__main__.B"
6963+
reveal_type(B()) # N: Revealed type is "__main__.A"
69646964

69656965
[case testNewReturnType10]
69666966
# https://github.com/python/mypy/issues/11398

test-data/unit/check-enum.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1360,7 +1360,7 @@ class Bar(Foo):
13601360
A = 1
13611361
B = 2
13621362

1363-
a = Bar.A
1363+
a = Bar.A # E: "Type[Foo]" has no attribute "A"
13641364
reveal_type(a.value) # N: Revealed type is "Any"
13651365
reveal_type(a._value_) # N: Revealed type is "Any"
13661366
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)