Skip to content

Commit

Permalink
Believe arbitrary __new__ return types
Browse files Browse the repository at this point in the history
Fixes python#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 python#16012
  • Loading branch information
hauntsaninja committed Sep 2, 2023
1 parent 2a6d9cb commit 4616fa2
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 5 deletions.
4 changes: 2 additions & 2 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,9 @@ def class_callable(
# by accident. Like `Hashable` is a subtype of `object`. See #11799
and isinstance(default_ret_type, Instance)
and not default_ret_type.type.is_protocol
# Only use the declared return type from __new__ or declared self in __init__
# Only use the declared return type from declared self in __init__
# if it is actually returning a subtype of what we would return otherwise.
and is_subtype(explicit_type, default_ret_type, ignore_type_params=True)
and (is_new or is_subtype(explicit_type, default_ret_type, ignore_type_params=True))
):
ret_type: Type = explicit_type
else:
Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -6883,7 +6883,7 @@ class A:
def __new__(cls) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")
pass

reveal_type(A()) # N: Revealed type is "__main__.A"
reveal_type(A()) # N: Revealed type is "builtins.int"

[case testNewReturnType4]
from typing import TypeVar, Type
Expand Down Expand Up @@ -6960,7 +6960,7 @@ class A:
class B(A):
pass

reveal_type(B()) # N: Revealed type is "__main__.B"
reveal_type(B()) # N: Revealed type is "__main__.A"

[case testNewReturnType10]
# https://github.com/python/mypy/issues/11398
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/check-enum.test
Original file line number Diff line number Diff line change
Expand Up @@ -1360,7 +1360,7 @@ class Bar(Foo):
A = 1
B = 2

a = Bar.A
a = Bar.A # E: "Type[Foo]" has no attribute "A"
reveal_type(a.value) # N: Revealed type is "Any"
reveal_type(a._value_) # N: Revealed type is "Any"
[builtins fixtures/primitives.pyi]
Expand Down

0 comments on commit 4616fa2

Please sign in to comment.