diff --git a/mypy/newsemanal/semanal.py b/mypy/newsemanal/semanal.py index eb0840be9d77..688186e6cd90 100644 --- a/mypy/newsemanal/semanal.py +++ b/mypy/newsemanal/semanal.py @@ -2686,17 +2686,7 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool: self.fail("Cannot declare the type of a type variable", s) return False - assert isinstance(s.rvalue, CallExpr) name = lvalue.name - names = self.current_symbol_table() - existing = names.get(name) - if existing and not (isinstance(existing.node, PlaceholderNode) or - # Also give error for another type variable with the same name. - (isinstance(existing.node, TypeVarExpr) and - existing.node is s.rvalue.analyzed)): - self.fail("Cannot redefine '%s' as a type variable" % name, s) - return False - if not self.check_typevar_name(call, name, s): return False @@ -2713,6 +2703,14 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool: return False variance, upper_bound = res + existing = self.current_symbol_table().get(name) + if existing and not (isinstance(existing.node, PlaceholderNode) or + # Also give error for another type variable with the same name. + (isinstance(existing.node, TypeVarExpr) and + existing.node is call.analyzed)): + self.fail("Cannot redefine '%s' as a type variable" % name, s) + return False + if self.options.disallow_any_unimported: for idx, constraint in enumerate(values, start=1): if has_any_from_unimported_type(constraint): diff --git a/test-data/unit/check-newsemanal.test b/test-data/unit/check-newsemanal.test index f8755b2ab7d4..aee4cd165a68 100644 --- a/test-data/unit/check-newsemanal.test +++ b/test-data/unit/check-newsemanal.test @@ -2774,3 +2774,14 @@ def g() -> None: nonlocal bar bar = [] # type: typing.List[int] # E: Name 'bar' already defined on line 11 [builtins fixtures/list.pyi] + +[case testNewAnalyzerMoreInvalidTypeVarArgumentsDeferred] +from typing import TypeVar, Generic + +defer: Yes + +S = TypeVar('S', covariant=True, contravariant=True) # E: TypeVar cannot be both covariant and contravariant \ + # E: "int" not callable + +class Yes: ... +[builtins fixtures/bool.pyi]