Skip to content

Make None compatible with Hashable #9371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,15 @@ def visit_any(self, left: AnyType) -> bool:

def visit_none_type(self, left: NoneType) -> bool:
if state.strict_optional:
return (isinstance(self.right, NoneType) or
is_named_instance(self.right, 'builtins.object') or
isinstance(self.right, Instance) and self.right.type.is_protocol and
not self.right.type.protocol_members)
if isinstance(self.right, NoneType) or is_named_instance(self.right,
'builtins.object'):
return True
if isinstance(self.right, Instance) and self.right.type.is_protocol:
members = self.right.type.protocol_members
# None is compatible with Hashable (and other similar protocols). This is
# slightly sloppy since we don't check the signature of "__hash__".
return not members or members == ["__hash__"]
return False
else:
return True

Expand Down
29 changes: 29 additions & 0 deletions test-data/unit/check-protocols.test
Original file line number Diff line number Diff line change
Expand Up @@ -2507,3 +2507,32 @@ class A(Protocol):
__slots__ = ()

[builtins fixtures/tuple.pyi]

[case testNoneVsProtocol]
# mypy: strict-optional
from typing_extensions import Protocol

class MyHashable(Protocol):
def __hash__(self) -> int: ...

def f(h: MyHashable) -> None: pass
f(None)

class Proto(Protocol):
def __hash__(self) -> int: ...
def method(self) -> None: ...

def g(h: Proto) -> None: pass
g(None) # E: Argument 1 to "g" has incompatible type "None"; expected "Proto"

class Proto2(Protocol):
def hash(self) -> None: ...

def h(h: Proto2) -> None: pass
h(None) # E: Argument 1 to "h" has incompatible type "None"; expected "Proto2"

class EmptyProto(Protocol): ...

def hh(h: EmptyProto) -> None: pass
hh(None)
[builtins fixtures/tuple.pyi]