Skip to content

Commit

Permalink
Add name lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p committed Feb 16, 2024
1 parent bbd59e9 commit 408e406
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 5 deletions.
10 changes: 5 additions & 5 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1956,13 +1956,13 @@ class Foo(Bar, Generic[T]): ...
for name, tvar_expr in declared_tvars:
tvar_expr_default = tvar_expr.default
if isinstance(tvar_expr_default, UnboundType):
# Assumption here is that the names cannot be duplicated
# TODO: - detect out of order and self-referencing TypeVars
# - nested default types, e.g. list[T1]
for fullname, type_var in self.tvar_scope.scope.items():
type_var_name = fullname.rpartition(".")[2]
if tvar_expr_default.name == type_var_name:
tvar_expr.default = type_var
n = self.lookup_qualified(
tvar_expr_default.name, tvar_expr_default, suppress_errors=True
)
if n is not None and (default := self.tvar_scope.get_binding(n)) is not None:
tvar_expr.default = default
tvar_def = self.tvar_scope.bind_new(name, tvar_expr)
tvar_defs.append(tvar_def)
return base_type_exprs, tvar_defs, is_protocol
Expand Down
30 changes: 30 additions & 0 deletions test-data/unit/check-typevar-defaults.test
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,36 @@ def func_d2(
n = ClassD2[int, float, str]()
reveal_type(n) # N: Revealed type is "__main__.ClassD2[builtins.int, builtins.float, builtins.str]"

[case testTypeVarDefaultsClassRecursiveMultipleFiles]
# flags: --disallow-any-generics
from typing import Generic, TypeVar
from file2 import T as T2

T = TypeVar('T', default=T2)

class ClassG1(Generic[T2, T]):
pass

def func(
a: ClassG1,
b: ClassG1[str],
c: ClassG1[str, float],
) -> None:
reveal_type(a) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]"
reveal_type(b) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]"
reveal_type(c) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]"

k = ClassG1()
reveal_type(k) # N: Revealed type is "__main__.ClassG1[builtins.int, builtins.int]"
l = ClassG1[str]()
reveal_type(l) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.str]"
m = ClassG1[str, float]()
reveal_type(m) # N: Revealed type is "__main__.ClassG1[builtins.str, builtins.float]"

[file file2.py]
from typing import TypeVar
T = TypeVar('T', default=int)

[case testTypeVarDefaultsTypeAlias1]
# flags: --disallow-any-generics
from typing import Any, Dict, List, Tuple, TypeVar, Union
Expand Down

0 comments on commit 408e406

Please sign in to comment.