diff --git a/mypy/semanal.py b/mypy/semanal.py index 08f9eb03c9d7..d7b50bd09496 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -1794,7 +1794,9 @@ def push_type_args( if self.is_defined_type_param(p.name): self.fail(f'"{p.name}" already defined as a type parameter', context) else: - self.add_symbol(p.name, tv, context, no_progress=True, type_param=True) + assert self.add_symbol( + p.name, tv, context, no_progress=True, type_param=True + ), "Type parameter should not be discarded" return tvs @@ -6830,6 +6832,7 @@ def add_symbol_table_node( else: # see note in docstring describing None contexts self.defer() + if ( existing is not None and context is not None @@ -6849,7 +6852,9 @@ def add_symbol_table_node( self.add_redefinition(names, name, symbol) if not (isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new)): self.name_already_defined(name, context, existing) - elif name not in self.missing_names[-1] and "*" not in self.missing_names[-1]: + elif type_param or ( + name not in self.missing_names[-1] and "*" not in self.missing_names[-1] + ): names[name] = symbol if not no_progress: self.progress = True diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index 6a72a7e4d5b5..be46ff6ee5c0 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -1228,6 +1228,43 @@ class C[T]: def f[S, S](x: S) -> S: # E: "S" already defined as a type parameter return x +[case testPEP695TypeVarNameClashNoCrashForwardReference] +# https://github.com/python/mypy/issues/18507 +from typing import TypeVar +T = TypeVar("T", bound=Foo) # E: Name "Foo" is used before definition + +class Foo: ... +class Bar[T]: ... + +[case testPEP695TypeVarNameClashNoCrashDeferredSymbol] +# https://github.com/python/mypy/issues/19526 +T = Unknown # E: Name "Unknown" is not defined + +class Foo[T]: ... +class Bar[*T]: ... +class Baz[**T]: ... +[builtins fixtures/tuple.pyi] + +[case testPEP695TypeVarNameClashTypeAlias] +type Tb = object +type Ta[Tb] = 'B[Tb]' +class A[Ta]: ... +class B[Tb](A[Ta]): ... + +[case testPEP695TypeVarNameClashStarImport] +# Similar to +# https://github.com/python/mypy/issues/19946 +import a + +[file a.py] +from b import * +class Foo[T]: ... + +[file b.py] +from a import * +class Bar[T]: ... +[builtins fixtures/tuple.pyi] + [case testPEP695ClassDecorator] from typing import Any