From 441e0437391f4ca640bd1c8d49dcc5df474c5c97 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Fri, 17 May 2024 14:08:23 +0100 Subject: [PATCH] Detect redefinitions of type parameters --- mypy/semanal.py | 15 ++++++++++++++- test-data/unit/check-python312.test | 12 ++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index fb337ce6f32f..1c90a3ea9b7a 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -1664,10 +1664,23 @@ def push_type_args( tvs.append((p.name, tv)) for name, tv in tvs: - self.add_symbol(name, tv, context, no_progress=True, type_param=True) + if self.is_defined_type_param(name): + self.fail(f'"{name}" already defined as a type parameter', context) + else: + self.add_symbol(name, tv, context, no_progress=True, type_param=True) return tvs + def is_defined_type_param(self, name: str) -> bool: + for names in self.locals: + if names is None: + continue + if name in names: + node = names[name].node + if isinstance(node, TypeVarLikeExpr): + return True + return False + def analyze_type_param(self, type_param: TypeParam) -> TypeVarLikeExpr | None: fullname = self.qualified_name(type_param.name) if type_param.upper_bound: diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index 97a6efbd64dc..3090c520f46f 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -1137,3 +1137,15 @@ class Outer: # Likewise, 'Inner' would not be available in these type annotations. def method1[T](self, a: Inner[T]) -> Inner[T]: return a + +[case testPEP695RedefineTypeParameterInScope] +# mypy: enable-incomplete-feature=NewGenericSyntax +class C[T]: + def m[T](self, x: T) -> T: # E: "T" already defined as a type parameter + return x + def m2(self) -> None: + def nested[T](x: T) -> T: # E: "T" already defined as a type parameter + return x + +def f[S, S](x: S) -> S: # E: "S" already defined as a type parameter + return x