Skip to content

Commit 7feaead

Browse files
committed
Bypass class attribute lookup for PEP 695 typevars
1 parent 4d82559 commit 7feaead

File tree

2 files changed

+15
-5
lines changed

2 files changed

+15
-5
lines changed

mypy/semanal.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1842,24 +1842,26 @@ def push_type_args(
18421842
return None
18431843
tvs.append((p.name, tv))
18441844

1845-
if self.is_defined_type_param(p.name):
1845+
if old_tv := self.is_defined_type_param(p.name):
18461846
self.fail(f'"{p.name}" already defined as a type parameter', context)
1847+
# we rely on the typevar being at self.locals[-1] later, so this needs to happen
1848+
self.add_symbol(p.name, old_tv, context, no_progress=True, type_param=True)
18471849
else:
18481850
assert self.add_symbol(
18491851
p.name, tv, context, no_progress=True, type_param=True
18501852
), "Type parameter should not be discarded"
18511853

18521854
return tvs
18531855

1854-
def is_defined_type_param(self, name: str) -> bool:
1856+
def is_defined_type_param(self, name: str) -> TypeVarLikeExpr | None:
18551857
for names in self.locals:
18561858
if names is None:
18571859
continue
18581860
if name in names:
18591861
node = names[name].node
18601862
if isinstance(node, TypeVarLikeExpr):
1861-
return True
1862-
return False
1863+
return node
1864+
return None
18631865

18641866
def analyze_type_param(
18651867
self, type_param: TypeParam, context: Context
@@ -2272,7 +2274,8 @@ class Foo(Bar, Generic[T]): ...
22722274
has_type_var_tuple = False
22732275
if defn.type_args is not None:
22742276
for p in defn.type_args:
2275-
node = self.lookup(p.name, context)
2277+
assert self.locals[-1], "expected PEP 695 type vars in locals"
2278+
node = self.locals[-1][p.name]
22762279
assert node is not None
22772280
assert isinstance(node.node, TypeVarLikeExpr)
22782281
if isinstance(node.node, TypeVarTupleExpr):

test-data/unit/check-python312.test

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,3 +2237,10 @@ class D[*Ts](Generic[Unpack[Us]]): # E: Generic[...] base class is redundant \
22372237
# E: Can only use one type var tuple in a class def
22382238
pass
22392239
[builtins fixtures/tuple.pyi]
2240+
2241+
[case testPEP695TypeVarReusedName]
2242+
class C:
2243+
X = 5
2244+
class Inner[X]:
2245+
pass
2246+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)