Skip to content

Commit 923b7d0

Browse files
committed
Add name lookup
1 parent 52ebbf2 commit 923b7d0

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

mypy/semanal.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1956,13 +1956,13 @@ class Foo(Bar, Generic[T]): ...
19561956
for name, tvar_expr in declared_tvars:
19571957
tvar_expr_default = tvar_expr.default
19581958
if isinstance(tvar_expr_default, UnboundType):
1959-
# Assumption here is that the names cannot be duplicated
1960-
# TODO: - detect out of order and self-referencing typevars
1959+
# TODO: - detect out of order and self-referencing TypeVars
19611960
# - nested default types, e.g. list[T1]
1962-
for fullname, type_var in self.tvar_scope.scope.items():
1963-
type_var_name = fullname.rpartition(".")[2]
1964-
if tvar_expr_default.name == type_var_name:
1965-
tvar_expr.default = type_var
1961+
n = self.lookup_qualified(
1962+
tvar_expr_default.name, tvar_expr_default, suppress_errors=True
1963+
)
1964+
if n is not None and (default := self.tvar_scope.get_binding(n)) is not None:
1965+
tvar_expr.default = default
19661966
tvar_def = self.tvar_scope.bind_new(name, tvar_expr)
19671967
tvar_defs.append(tvar_def)
19681968
return base_type_exprs, tvar_defs, is_protocol

test-data/unit/check-typevar-defaults.test

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,36 @@ def func_d2(
425425
n = ClassD2[int, float, str]()
426426
reveal_type(n) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.str]"
427427

428+
[case testTypeVarDefaultsClassRecursiveMultipleFiles]
429+
# flags: --disallow-any-generics
430+
from typing import Generic, TypeVar
431+
from file2 import T as T2
432+
433+
T = TypeVar('T', default=T2)
434+
435+
class ClassG1(Generic[T2, T]):
436+
pass
437+
438+
def func(
439+
a: ClassG1,
440+
b: ClassG1[str],
441+
c: ClassG1[str, float],
442+
) -> None:
443+
reveal_type(a) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]"
444+
reveal_type(b) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]"
445+
reveal_type(c) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]"
446+
447+
k = ClassG1()
448+
reveal_type(k) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]"
449+
l = ClassG1[str]()
450+
reveal_type(l) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]"
451+
m = ClassG1[str, float]()
452+
reveal_type(m) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]"
453+
454+
[file file2.py]
455+
from typing import TypeVar
456+
T = TypeVar('T', default=int)
457+
428458
[case testTypeVarDefaultsTypeAlias1]
429459
# flags: --disallow-any-generics
430460
from typing import Any, Dict, List, Tuple, TypeVar, Union

0 commit comments

Comments
 (0)