From 3ea101eed53e3bdb5ecf5273257ea457ddf3de10 Mon Sep 17 00:00:00 2001 From: Lukasz Langa Date: Mon, 19 Dec 2016 13:52:17 -0800 Subject: [PATCH] Fixes #2589: type redeclarations cause spurious warnings 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. --- mypy/semanal.py | 5 +++-- test-data/unit/semanal-errors.test | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/mypy/semanal.py b/mypy/semanal.py index 9a7ef1f6282a8..8771fb768d80f 100644 --- a/mypy/semanal.py +++ b/mypy/semanal.py @@ -1309,10 +1309,11 @@ def analyze_lvalue(self, lval: Lvalue, nested: bool = False, lval.kind = MDEF lval.fullname = lval.name self.type.names[lval.name] = SymbolTableNode(MDEF, v) + elif explicit_type: + # Don't re-bind types + self.name_already_defined(lval.name, lval) else: # Bind to an existing name. - if explicit_type: - self.name_already_defined(lval.name, lval) lval.accept(self) self.check_lvalue_validity(lval.node, lval) elif isinstance(lval, MemberExpr): diff --git a/test-data/unit/semanal-errors.test b/test-data/unit/semanal-errors.test index cc222d9799b74..06fd3d0dd2261 100644 --- a/test-data/unit/semanal-errors.test +++ b/test-data/unit/semanal-errors.test @@ -1311,3 +1311,13 @@ class A: [out] main:5: error: Name 'x' is not defined main:5: error: Name 'y' is not defined + +[case testTypeRedeclarationNoSpuriousWarnings] +from typing import Tuple +a = 1 # type: int +a = 's' # type: str +a = ('spam', 'spam', 'eggs', 'spam') # type: Tuple[str] + +[out] +main:3: error: Name 'a' already defined +main:4: error: Name 'a' already defined