Skip to content

reportUnhashable in isinstance(x, set) clause when using recursive TypeAlias. #7824

Closed as not planned

Description

Code sample in pyright playground

from typing import TypeVar, TypeAlias, Any, reveal_type
from collections.abc import Collection, Mapping

T_co = TypeVar("T_co", covariant=True)
Nested: TypeAlias = T_co | Collection["Nested[T_co]"] | Mapping[Any, "Nested[T_co]"]

def foo(obj: T_co | Collection[T_co] | Mapping[Any, T_co]) -> set:
    if isinstance(obj, set):
        reveal_type(obj)  # set[Unknown]* | set[T_co@foo]
        return {x for x in obj} # ✅
    raise TypeError

def bar(obj: Nested[T_co]) -> set:
    if isinstance(obj, set):
        reveal_type(obj)  # set[Unknown]* | set[Nested[T_co@bar]]
        return {x for x in obj} # ❌ reportUnhashable
    raise TypeError

mypy reports no issues, and reports types as set[Any] in each case.

Activity

  1. erictraut commented on May 2, 2024

    @erictraut
    Collaborator

    This behavior is intended, so I don't consider this a bug.

    A Mapping object does not meet the requirements of hashability, so if you attempt to add a Mapping object to a set, you will see an error:

    def func1(obj: Mapping):
        x = {obj} # Type error: obj is not hashable

    In your first example (foo), you are using a type guard to narrow the type of obj from T_co | Collection[T_co] | Mapping[Any, T_co] to T_co | Collection[T_co], so when you iterate over the items in each of these, you do not receive any Mapping object.

    In your second example (bar), when you iterate over the items in obj, one of the subtypes is Mapping`, which is not hashable.

    Mypy doesn't emit an error here because it doesn't provide checks for hashability.

    If you don't want pyright to check for hashability, you can disable the reportUnhashable check.

  2. added
    as designed
    on May 2, 2024
  3. randolf-scholz commented on May 2, 2024

    @randolf-scholz
    Author

    Eric Traut (@erictraut) We already know it's a set inside the if isinstance clause, so it is known that the elements are hashable! After your comment, I checked typeshed and was surprised that they do not bind the TypeVar of set to Hashable:

    https://github.com/python/typeshed/blob/5883898b0ab08b7ad306e37ca70dd9e646b4ce2e/stdlib/builtins.pyi#L1111

    python/typeshed#9571

    This seems to be the real underlying issue here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    as designedbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions