Skip to content

Commit b0e36aa

Browse files
authored
Fix faulty casts in checker (#10560)
Fixes #9615, fixes #9682 Both issue reports hit the faulty cast on L2803. This changes the logic so that that cast is actually always true. If not, we just end up doing whatever the fallback else clause does; this resulted in behaviour that matched what I expected. After that, the #9682 hit another crash in checker.py, where var.node was None instead of a Var. It seemed reasonable to just branch instead. Co-authored-by: hauntsaninja <>
1 parent 7f54bd0 commit b0e36aa

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

mypy/checker.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2807,7 +2807,9 @@ def check_lvalue(self, lvalue: Lvalue) -> Tuple[Optional[Type],
28072807
index_lvalue = None
28082808
inferred = None
28092809

2810-
if self.is_definition(lvalue):
2810+
if self.is_definition(lvalue) and (
2811+
not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)
2812+
):
28112813
if isinstance(lvalue, NameExpr):
28122814
inferred = cast(Var, lvalue.node)
28132815
assert isinstance(inferred, Var)
@@ -3430,7 +3432,8 @@ def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:
34303432
source = ('(exception variable "{}", which we do not '
34313433
'accept outside except: blocks even in '
34323434
'python 2)'.format(var.name))
3433-
cast(Var, var.node).type = DeletedType(source=source)
3435+
if isinstance(var.node, Var):
3436+
var.node.type = DeletedType(source=source)
34343437
self.binder.cleanse(var)
34353438
if s.else_body:
34363439
self.accept(s.else_body)

test-data/unit/check-redefine.test

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,3 +474,12 @@ with A() as x:
474474
reveal_type(x) # N: Revealed type is "builtins.int"
475475
with B() as x:
476476
x = 0 # E: Incompatible types in assignment (expression has type "int", variable has type "str")
477+
478+
479+
[case testRedefineModuleAsException]
480+
import typing
481+
try:
482+
pass
483+
except Exception as typing:
484+
pass
485+
[builtins fixtures/exception.pyi]

test-data/unit/check-unreachable-code.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1327,3 +1327,19 @@ async def f_malformed_2() -> int:
13271327

13281328
[typing fixtures/typing-full.pyi]
13291329
[builtins fixtures/tuple.pyi]
1330+
1331+
1332+
[case testConditionalTypeVarException]
1333+
# every part of this test case was necessary to trigger the crash
1334+
import sys
1335+
from typing import TypeVar
1336+
1337+
T = TypeVar("T", int, str)
1338+
1339+
def f(t: T) -> None:
1340+
if sys.platform == "lol":
1341+
try:
1342+
pass
1343+
except BaseException as e:
1344+
pass
1345+
[builtins fixtures/dict.pyi]

0 commit comments

Comments
 (0)