Skip to content

Commit 6fa04e4

Browse files
authored
Improve interaction between --local-partial-types and hashability (python#20719)
Without this, we would reveal `list[Hashable]` in the test case This isn't a great fix though...
1 parent e63e6e5 commit 6fa04e4

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

mypy/checker.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4470,6 +4470,14 @@ def infer_variable_type(
44704470
is_lvalue_final=name.is_final,
44714471
is_lvalue_member=isinstance(lvalue, MemberExpr),
44724472
)
4473+
and not (
4474+
# Trust None assignments to dunder methods
4475+
# This is a bit ad-hoc, but it improves protocol
4476+
# (non-)assignability, for instance `__hash__ = None`
4477+
self.scope.active_class()
4478+
and is_dunder(name.name)
4479+
and isinstance(get_proper_type(init_type), NoneType)
4480+
)
44734481
and not self.no_partial_types
44744482
):
44754483
# We cannot use the type of the initialization expression for full type

test-data/unit/check-protocols.test

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2940,7 +2940,25 @@ class Gleemer:
29402940

29412941

29422942
[case testPartialTypeProtocolHashable]
2943-
# flags: --no-strict-optional
2943+
# flags: --no-strict-optional --no-local-partial-types
2944+
from typing import Protocol
2945+
2946+
class Hashable(Protocol):
2947+
def __hash__(self) -> int: ...
2948+
2949+
class ObjectHashable:
2950+
def __hash__(self) -> int: ...
2951+
2952+
class DataArray(ObjectHashable):
2953+
__hash__ = None
2954+
2955+
def f(self, x: Hashable) -> None:
2956+
reveal_type([self, x]) # N: Revealed type is "builtins.list[builtins.object]"
2957+
[builtins fixtures/tuple.pyi]
2958+
2959+
2960+
[case testPartialTypeProtocolHashableLocalPartialTypes]
2961+
# flags: --no-strict-optional --local-partial-types
29442962
from typing import Protocol
29452963

29462964
class Hashable(Protocol):

0 commit comments

Comments
 (0)