Skip to content

[PEP 696] Fix swapping TypeVars with defaults. #19449

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 3 additions & 3 deletions mypy/expandtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,9 +250,9 @@ def visit_type_var(self, t: TypeVarType) -> Type:
if (tvar_id := repl.id) in self.recursive_tvar_guard:
return self.recursive_tvar_guard[tvar_id] or repl
self.recursive_tvar_guard[tvar_id] = None
repl = repl.accept(self)
if isinstance(repl, TypeVarType):
repl.default = repl.default.accept(self)
repl.default = repl.default.accept(self)
expanded = repl.accept(self) # Note: `expanded is repl` may be true.
repl = repl if isinstance(expanded, TypeVarType) else expanded
self.recursive_tvar_guard[tvar_id] = repl
return repl

Expand Down
32 changes: 32 additions & 0 deletions test-data/unit/check-typevar-defaults.test
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,38 @@ def func_c4(
reveal_type(m) # N: Revealed type is "__main__.ClassC4[builtins.int, builtins.float]"
[builtins fixtures/tuple.pyi]

[case testTypeVarDefaultsSwap]
from typing import TypeVar, Generic

T = TypeVar("T")
X = TypeVar("X", default=object)
Y = TypeVar("Y", default=object)


class Foo(Generic[T, Y]):
def test(self) -> None:
reveal_type( Foo[Y, T]() ) # N: Revealed type is "__main__.Foo[Y`2 = builtins.object, T`1]"


class Bar(Generic[X, Y]):
def test(self) -> None:
reveal_type( Bar[Y, X]() ) # N: Revealed type is "__main__.Bar[Y`2 = builtins.object, X`1 = builtins.object]"


[case testTypeVarDefaultsSwap2]
from typing import TypeVar, Generic

X = TypeVar("X", default=object)
Y = TypeVar("Y", default=object)
U = TypeVar("U", default=object)
V = TypeVar("V", default=object)

class Transform(Generic[X, Y]):
def invert(self) -> "Transform[Y, X]": ...

class Foo(Transform[U, V], Generic[U, V]):
def invert(self) -> "Foo[V, U]": ...

[case testTypeVarDefaultsClassRecursive1]
# flags: --disallow-any-generics
from typing import Generic, TypeVar, List
Expand Down