Skip to content

Commit ca2d2c6

Browse files
ambvJukkaL
authored andcommitted
Fixes #2589: type redeclarations cause spurious warnings (#2591)
This addresses the problem by refusing to re-bind the explit type for a name once one type was already present. This means it changes the logic from "last type declaration wins" to "first type declaration wins". The error about redeclaring the type is still being reported but the type does not change, which changes the errors given, producing less surprising results. Test plan: added a new test case to unit/semanal. Without the change, there's spurious errors about names not conforming to the type defined last. With the change, only the "Name already defined" errors remain.
1 parent eaa7e6b commit ca2d2c6

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

mypy/semanal.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1309,10 +1309,11 @@ def analyze_lvalue(self, lval: Lvalue, nested: bool = False,
13091309
lval.kind = MDEF
13101310
lval.fullname = lval.name
13111311
self.type.names[lval.name] = SymbolTableNode(MDEF, v)
1312+
elif explicit_type:
1313+
# Don't re-bind types
1314+
self.name_already_defined(lval.name, lval)
13121315
else:
13131316
# Bind to an existing name.
1314-
if explicit_type:
1315-
self.name_already_defined(lval.name, lval)
13161317
lval.accept(self)
13171318
self.check_lvalue_validity(lval.node, lval)
13181319
elif isinstance(lval, MemberExpr):

test-data/unit/semanal-errors.test

+10
Original file line numberDiff line numberDiff line change
@@ -1311,3 +1311,13 @@ class A:
13111311
[out]
13121312
main:5: error: Name 'x' is not defined
13131313
main:5: error: Name 'y' is not defined
1314+
1315+
[case testTypeRedeclarationNoSpuriousWarnings]
1316+
from typing import Tuple
1317+
a = 1 # type: int
1318+
a = 's' # type: str
1319+
a = ('spam', 'spam', 'eggs', 'spam') # type: Tuple[str]
1320+
1321+
[out]
1322+
main:3: error: Name 'a' already defined
1323+
main:4: error: Name 'a' already defined

0 commit comments

Comments
 (0)