Skip to content

Commit

Permalink
Type parameters are not in scope in class decorators
Browse files Browse the repository at this point in the history
  • Loading branch information
JukkaL committed May 17, 2024
1 parent 1717ac1 commit 007f4a4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1814,8 +1814,18 @@ def analyze_class(self, defn: ClassDef) -> None:
defn.info.is_protocol = is_protocol
self.recalculate_metaclass(defn, declared_metaclass)
defn.info.runtime_protocol = False

if defn.type_args:
# PEP 695 type parameters are not in scope in class decorators, so
# temporarily disable type parameter namespace.
type_params_names = self.locals.pop()
self.scope_stack.pop()
for decorator in defn.decorators:
self.analyze_class_decorator(defn, decorator)
if defn.type_args:
self.locals.append(type_params_names)
self.scope_stack.append(SCOPE_ANNOTATION)

self.analyze_class_body_common(defn)

def setup_type_vars(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]) -> None:
Expand Down
12 changes: 12 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -1149,3 +1149,15 @@ class C[T]:

def f[S, S](x: S) -> S: # E: "S" already defined as a type parameter
return x

[case testPEP695ClassDecorator]
# mypy: enable-incomplete-feature=NewGenericSyntax
from typing import Any

T = 0

def decorator(x: str) -> Any: ...

@decorator(T) # E: Argument 1 to "decorator" has incompatible type "int"; expected "str"
class C[T]:
pass

0 comments on commit 007f4a4

Please sign in to comment.