python / typing_extensions

Backported and experimental type hints for Python
Other
445 stars 109 forks source link

Backport of "_collect_type_vars" behaves wrong if Unpack is used on generic non-TypeVarTuple types #471

Closed Daraan closed 1 month ago

Daraan commented 1 month ago

Consider the following two cases, which only should yield a single type_var T.

# Python < 3.11
from typing_extensions import Unpack, TypeVarTuple, _collect_type_vars, Tuple, TypeVar, TypedDict, Generic
Ts = TypeVarTuple("Ts")
T= TypeVar("T")

class Movie(Generic[T], TypedDict):; 
    genre : T

print(_collect_type_vars([Unpack[Movie[T]]]))
# (typing_extensions.Unpack[typing_extensions.Movie[~T]], ~T)

print(_collect_type_vars([Unpack[Tuple[T]]]))
# (typing_extensions.Unpack[typing.Tuple[~T]], ~T)

The problem is that the second condition isinstance(Unpack_instance, TypeVar) is True, which appends the unpack variable itself which makes no sense.

typing_extensions monkey patches this function in the typing module