diff --git a/mypy/checker.py b/mypy/checker.py index dde8a3441c35..556f0ee13104 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -2796,7 +2796,9 @@ def check_lvalue(self, lvalue: Lvalue) -> Tuple[Optional[Type], index_lvalue = None inferred = None - if self.is_definition(lvalue): + if self.is_definition(lvalue) and ( + not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var) + ): if isinstance(lvalue, NameExpr): inferred = cast(Var, lvalue.node) assert isinstance(inferred, Var) @@ -3420,7 +3422,8 @@ def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None: source = ('(exception variable "{}", which we do not ' 'accept outside except: blocks even in ' 'python 2)'.format(var.name)) - cast(Var, var.node).type = DeletedType(source=source) + if isinstance(var.node, Var): + var.node.type = DeletedType(source=source) self.binder.cleanse(var) if s.else_body: self.accept(s.else_body) diff --git a/test-data/unit/check-redefine.test b/test-data/unit/check-redefine.test index 5530777dd4db..4ac56edb24ef 100644 --- a/test-data/unit/check-redefine.test +++ b/test-data/unit/check-redefine.test @@ -474,3 +474,12 @@ with A() as x: reveal_type(x) # N: Revealed type is "builtins.int" with B() as x: x = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "str") + + +[case testRedefineModuleAsException] +import typing +try: + pass +except Exception as typing: + pass +[builtins fixtures/exception.pyi] diff --git a/test-data/unit/check-unreachable-code.test b/test-data/unit/check-unreachable-code.test index e4235e82fc98..21b0f1f0c60f 100644 --- a/test-data/unit/check-unreachable-code.test +++ b/test-data/unit/check-unreachable-code.test @@ -1305,3 +1305,19 @@ async def f_malformed_2() -> int: [typing fixtures/typing-full.pyi] [builtins fixtures/tuple.pyi] + + +[case testConditionalTypeVarException] +# every part of this test case was necessary to trigger the crash +import sys +from typing import TypeVar + +T = TypeVar("T", int, str) + +def f(t: T) -> None: + if sys.platform == "lol": + try: + pass + except BaseException as e: + pass +[builtins fixtures/dict.pyi]