You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type[object] isn't hashable, and can't be asserted to be Hashable #12993
Context: mypy doesn't regard Type[object] as Hashable. (It is possible with metaclasses that this might be the case, LSP concerns aside.) It rightly complains when Type[object] is used where a Hashable is required.
The issue is that mypy assumes Type[object]cannot be Hashable, even following an assertion, making the above difficult to work around.
importcollectionsimportfunctoolsimporttypingfromtypingimport (
Type,
)
@functools.lru_cache(maxsize=None)defcached_function(type_: Type[object]) ->bool:
# expensive computation here_=type_returnTruedeffunction1(type_: Type[object]) ->None:
# it's theoretically possible for a Type[...] object to be# unhashable (although this would seem to violate the Liskov# Substitution Principle, LSP)assertcached_function(type_)
# actual, as expected:# error: Argument 1 to "__call__" of# "_lru_cache_wrapper" has incompatible type# "Type[object]"; expected "Hashable" [arg-type]deffunction1a(type_: Type[object]) ->None:
# we attempt to assure mypy that 'type_' is Hashableassertisinstance(type_, typing.Hashable)
reveal_type(type_)
# expected: revealed type is: ...# actual: prints nothing; mypy believes this is unreachableassertcached_function(type_)
# expected: no warning# actual: mypy believes this is unreachabledeffunction1b(type_: Type[object]) ->None:
# we attempt to assure mypy that 'type_' is Hashableassertisinstance(type_, collections.abc.Hashable)
reveal_type(type_)
# expected: revealed type is: ...# actual: prints nothing; mypy believes this is unreachableassertcached_function(type_)
# expected: no warning# actual: mypy believes this is unreachable
Expected Behavior
Adding assert isinstance(..., Hashable) should work around this problem.
Actual Behavior
Asserting that a variable having type Type[object] is Hashable causes mypy to conclude the code is unreachable.
Your Environment
Mypy version used: 0.961 and master (on mypy-play.net)
Activity
AlexWaygood commentedon Jun 17, 2022
Duplicate of #11470
type[Any]not consideredHashable#11470finite-state-machine commentedon Jun 17, 2022
So it is. My apologies!