Skip to content
Closed
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
12 changes: 8 additions & 4 deletions mypy/expandtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,10 +246,14 @@ 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)
self.recursive_tvar_guard[tvar_id] = repl
expanded = repl.accept(self)

if isinstance(expanded, TypeVarType):
expanded.default = expanded.default.accept(self)
else:
repl = expanded
Comment on lines +251 to +254
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe more readable if done the other way round?

expanded = repl.accept(self)
if not isinstance(expanded, TypeVarType):
    repl = expanded
else:
    expanded.default = expanded.default.accept(self)


self.recursive_tvar_guard[tvar_id] = expanded
return repl

def visit_param_spec(self, t: ParamSpecType) -> Type:
Expand Down
18 changes: 18 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,24 @@ 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, Y`2 = builtins.object]"


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