Skip to content

Commit cded69d

Browse files
ilevkivskyiJukkaL
authored andcommitted
Complain abaout redefinition after only after we decided it is valid (#7093)
Fixes #6957 Using the opportunity, I do a tiny refactoring. The only change in the logic is switching the order of things.
1 parent 8030804 commit cded69d

2 files changed

Lines changed: 19 additions & 10 deletions

File tree

mypy/newsemanal/semanal.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2686,17 +2686,7 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool:
26862686
self.fail("Cannot declare the type of a type variable", s)
26872687
return False
26882688

2689-
assert isinstance(s.rvalue, CallExpr)
26902689
name = lvalue.name
2691-
names = self.current_symbol_table()
2692-
existing = names.get(name)
2693-
if existing and not (isinstance(existing.node, PlaceholderNode) or
2694-
# Also give error for another type variable with the same name.
2695-
(isinstance(existing.node, TypeVarExpr) and
2696-
existing.node is s.rvalue.analyzed)):
2697-
self.fail("Cannot redefine '%s' as a type variable" % name, s)
2698-
return False
2699-
27002690
if not self.check_typevar_name(call, name, s):
27012691
return False
27022692

@@ -2713,6 +2703,14 @@ def process_typevar_declaration(self, s: AssignmentStmt) -> bool:
27132703
return False
27142704
variance, upper_bound = res
27152705

2706+
existing = self.current_symbol_table().get(name)
2707+
if existing and not (isinstance(existing.node, PlaceholderNode) or
2708+
# Also give error for another type variable with the same name.
2709+
(isinstance(existing.node, TypeVarExpr) and
2710+
existing.node is call.analyzed)):
2711+
self.fail("Cannot redefine '%s' as a type variable" % name, s)
2712+
return False
2713+
27162714
if self.options.disallow_any_unimported:
27172715
for idx, constraint in enumerate(values, start=1):
27182716
if has_any_from_unimported_type(constraint):

test-data/unit/check-newsemanal.test

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2774,3 +2774,14 @@ def g() -> None:
27742774
nonlocal bar
27752775
bar = [] # type: typing.List[int] # E: Name 'bar' already defined on line 11
27762776
[builtins fixtures/list.pyi]
2777+
2778+
[case testNewAnalyzerMoreInvalidTypeVarArgumentsDeferred]
2779+
from typing import TypeVar, Generic
2780+
2781+
defer: Yes
2782+
2783+
S = TypeVar('S', covariant=True, contravariant=True) # E: TypeVar cannot be both covariant and contravariant \
2784+
# E: "int" not callable
2785+
2786+
class Yes: ...
2787+
[builtins fixtures/bool.pyi]

0 commit comments

Comments
 (0)