Skip to content

Commit e93a700

Browse files
hauntsaninjaJukkaL
authored andcommitted
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 784aa93 commit e93a700

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
@@ -2796,7 +2796,9 @@ def check_lvalue(self, lvalue: Lvalue) -> Tuple[Optional[Type],
27962796
index_lvalue = None
27972797
inferred = None
27982798

2799-
if self.is_definition(lvalue):
2799+
if self.is_definition(lvalue) and (
2800+
not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var)
2801+
):
28002802
if isinstance(lvalue, NameExpr):
28012803
inferred = cast(Var, lvalue.node)
28022804
assert isinstance(inferred, Var)
@@ -3420,7 +3422,8 @@ def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:
34203422
source = ('(exception variable "{}", which we do not '
34213423
'accept outside except: blocks even in '
34223424
'python 2)'.format(var.name))
3423-
cast(Var, var.node).type = DeletedType(source=source)
3425+
if isinstance(var.node, Var):
3426+
var.node.type = DeletedType(source=source)
34243427
self.binder.cleanse(var)
34253428
if s.else_body:
34263429
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
@@ -1305,3 +1305,19 @@ async def f_malformed_2() -> int:
13051305

13061306
[typing fixtures/typing-full.pyi]
13071307
[builtins fixtures/tuple.pyi]
1308+
1309+
1310+
[case testConditionalTypeVarException]
1311+
# every part of this test case was necessary to trigger the crash
1312+
import sys
1313+
from typing import TypeVar
1314+
1315+
T = TypeVar("T", int, str)
1316+
1317+
def f(t: T) -> None:
1318+
if sys.platform == "lol":
1319+
try:
1320+
pass
1321+
except BaseException as e:
1322+
pass
1323+
[builtins fixtures/dict.pyi]

0 commit comments

Comments
 (0)