Skip to content

Recognize Hashable as a real protocol, refs #11799 #11802

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 2 commits into from
Mar 24, 2022
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
4 changes: 4 additions & 0 deletions mypy/typeops.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance,
explicit_type = init_ret_type if is_new else orig_self_type
if (
isinstance(explicit_type, (Instance, TupleType))
# We have to skip protocols, because it can can be a subtype of a return type
# 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__
# 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)
Expand Down
13 changes: 13 additions & 0 deletions test-data/unit/pythoneval.test
Original file line number Diff line number Diff line change
Expand Up @@ -1575,6 +1575,19 @@ reveal_type(x) # Revealed type is "collections.OrderedDict[builtins.str, builti
[out]
_testTypingExtensionsOrderedDictAlias.py:3: note: Revealed type is "collections.OrderedDict[builtins.str, builtins.str]"

[case testSpecialTypingProtocols]
# flags: --warn-unreachable
from typing import Awaitable, Hashable, Union, Tuple, List

obj: Union[Tuple[int], List[int]]
if isinstance(obj, Hashable):
reveal_type(obj)
if isinstance(obj, Awaitable):
reveal_type(obj)
[out]
_testSpecialTypingProtocols.py:6: note: Revealed type is "Tuple[builtins.int]"
_testSpecialTypingProtocols.py:8: error: Statement is unreachable

[case testEnumValueWithPlaceholderNodeType]
# https://github.com/python/mypy/issues/11971
from enum import Enum
Expand Down