Skip to content

Commit 85b6f12

Browse files
committed
Revert "Now typechecks traceback in raise e, msg, traceback on py2 (#11289)"
This reverts commit c22beb4. See #11742 for context.
1 parent b2c9296 commit 85b6f12

File tree

4 files changed

+19
-145
lines changed

4 files changed

+19
-145
lines changed

mypy/checker.py

Lines changed: 12 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -3492,7 +3492,7 @@ def visit_raise_stmt(self, s: RaiseStmt) -> None:
34923492
if s.expr:
34933493
self.type_check_raise(s.expr, s)
34943494
if s.from_expr:
3495-
self.type_check_raise(s.from_expr, s, optional=True)
3495+
self.type_check_raise(s.from_expr, s, True)
34963496
self.binder.unreachable()
34973497

34983498
def type_check_raise(self, e: Expression, s: RaiseStmt,
@@ -3501,88 +3501,24 @@ def type_check_raise(self, e: Expression, s: RaiseStmt,
35013501
if isinstance(typ, DeletedType):
35023502
self.msg.deleted_as_rvalue(typ, e)
35033503
return
3504-
3505-
if self.options.python_version[0] == 2:
3506-
# Since `raise` has very different rule on python2, we use a different helper.
3507-
# https://github.com/python/mypy/pull/11289
3508-
self._type_check_raise_python2(e, s, typ)
3509-
return
3510-
3511-
# Python3 case:
35123504
exc_type = self.named_type('builtins.BaseException')
3513-
expected_type_items = [exc_type, TypeType(exc_type)]
3505+
expected_type = UnionType([exc_type, TypeType(exc_type)])
35143506
if optional:
3515-
# This is used for `x` part in a case like `raise e from x`,
3516-
# where we allow `raise e from None`.
3517-
expected_type_items.append(NoneType())
3518-
3519-
self.check_subtype(
3520-
typ, UnionType.make_union(expected_type_items), s,
3521-
message_registry.INVALID_EXCEPTION,
3522-
)
3507+
expected_type.items.append(NoneType())
3508+
if self.options.python_version[0] == 2:
3509+
# allow `raise type, value, traceback`
3510+
# https://docs.python.org/2/reference/simple_stmts.html#the-raise-statement
3511+
# TODO: Also check tuple item types.
3512+
any_type = AnyType(TypeOfAny.implementation_artifact)
3513+
tuple_type = self.named_type('builtins.tuple')
3514+
expected_type.items.append(TupleType([any_type, any_type], tuple_type))
3515+
expected_type.items.append(TupleType([any_type, any_type, any_type], tuple_type))
3516+
self.check_subtype(typ, expected_type, s, message_registry.INVALID_EXCEPTION)
35233517

35243518
if isinstance(typ, FunctionLike):
35253519
# https://github.com/python/mypy/issues/11089
35263520
self.expr_checker.check_call(typ, [], [], e)
35273521

3528-
def _type_check_raise_python2(self, e: Expression, s: RaiseStmt, typ: ProperType) -> None:
3529-
# Python2 has two possible major cases:
3530-
# 1. `raise expr`, where `expr` is some expression, it can be:
3531-
# - Exception typ
3532-
# - Exception instance
3533-
# - Old style class (not supported)
3534-
# - Tuple, where 0th item is exception type or instance
3535-
# 2. `raise exc, msg, traceback`, where:
3536-
# - `exc` is exception type (not instance!)
3537-
# - `traceback` is `types.TracebackType | None`
3538-
# Important note: `raise exc, msg` is not the same as `raise (exc, msg)`
3539-
# We call `raise exc, msg, traceback` - legacy mode.
3540-
exc_type = self.named_type('builtins.BaseException')
3541-
3542-
if (not s.legacy_mode and (isinstance(typ, TupleType) and typ.items
3543-
or (isinstance(typ, Instance) and typ.args
3544-
and typ.type.fullname == 'builtins.tuple'))):
3545-
# `raise (exc, ...)` case:
3546-
item = typ.items[0] if isinstance(typ, TupleType) else typ.args[0]
3547-
self.check_subtype(
3548-
item, UnionType([exc_type, TypeType(exc_type)]), s,
3549-
'When raising a tuple, first element must by derived from BaseException',
3550-
)
3551-
return
3552-
elif s.legacy_mode:
3553-
# `raise Exception, msg` case
3554-
# `raise Exception, msg, traceback` case
3555-
# https://docs.python.org/2/reference/simple_stmts.html#the-raise-statement
3556-
assert isinstance(typ, TupleType) # Is set in fastparse2.py
3557-
self.check_subtype(
3558-
typ.items[0], TypeType(exc_type), s,
3559-
'First argument must be BaseException subtype',
3560-
)
3561-
3562-
# Typecheck `traceback` part:
3563-
if len(typ.items) == 3:
3564-
# Now, we typecheck `traceback` argument if it is present.
3565-
# We do this after the main check for better error message
3566-
# and better ordering: first about `BaseException` subtype,
3567-
# then about `traceback` type.
3568-
traceback_type = UnionType.make_union([
3569-
self.named_type('types.TracebackType'),
3570-
NoneType(),
3571-
])
3572-
self.check_subtype(
3573-
typ.items[2], traceback_type, s,
3574-
'Third argument to raise must have "{}" type'.format(traceback_type),
3575-
)
3576-
else:
3577-
expected_type_items = [
3578-
# `raise Exception` and `raise Exception()` cases:
3579-
exc_type, TypeType(exc_type),
3580-
]
3581-
self.check_subtype(
3582-
typ, UnionType.make_union(expected_type_items),
3583-
s, message_registry.INVALID_EXCEPTION,
3584-
)
3585-
35863522
def visit_try_stmt(self, s: TryStmt) -> None:
35873523
"""Type check a try statement."""
35883524
# Our enclosing frame will get the result if the try/except falls through.

mypy/fastparse2.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -664,23 +664,19 @@ def visit_With(self, n: ast27.With) -> WithStmt:
664664
typ)
665665
return self.set_line(stmt, n)
666666

667-
# 'raise' [test [',' test [',' test]]]
668667
def visit_Raise(self, n: ast27.Raise) -> RaiseStmt:
669-
legacy_mode = False
670668
if n.type is None:
671669
e = None
672670
else:
673671
if n.inst is None:
674672
e = self.visit(n.type)
675673
else:
676-
legacy_mode = True
677674
if n.tback is None:
678675
e = TupleExpr([self.visit(n.type), self.visit(n.inst)])
679676
else:
680677
e = TupleExpr([self.visit(n.type), self.visit(n.inst), self.visit(n.tback)])
681678

682679
stmt = RaiseStmt(e, None)
683-
stmt.legacy_mode = legacy_mode
684680
return self.set_line(stmt, n)
685681

686682
# TryExcept(stmt* body, excepthandler* handlers, stmt* orelse)

mypy/nodes.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1294,19 +1294,16 @@ def accept(self, visitor: StatementVisitor[T]) -> T:
12941294

12951295

12961296
class RaiseStmt(Statement):
1297-
__slots__ = ('expr', 'from_expr', 'legacy_mode')
1297+
__slots__ = ('expr', 'from_expr')
12981298

12991299
# Plain 'raise' is a valid statement.
13001300
expr: Optional[Expression]
13011301
from_expr: Optional[Expression]
1302-
# Is set when python2 has `raise exc, msg, traceback`.
1303-
legacy_mode: bool
13041302

13051303
def __init__(self, expr: Optional[Expression], from_expr: Optional[Expression]) -> None:
13061304
super().__init__()
13071305
self.expr = expr
13081306
self.from_expr = from_expr
1309-
self.legacy_mode = False
13101307

13111308
def accept(self, visitor: StatementVisitor[T]) -> T:
13121309
return visitor.visit_raise_stmt(self)

test-data/unit/check-python2.test

Lines changed: 6 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -68,73 +68,18 @@ A.f(1)
6868
A.f('') # E: Argument 1 to "f" of "A" has incompatible type "str"; expected "int"
6969
[builtins_py2 fixtures/staticmethod.pyi]
7070

71+
[case testRaiseTuple]
72+
import typing
73+
raise BaseException, "a"
74+
raise BaseException, "a", None
75+
[builtins_py2 fixtures/exception.pyi]
76+
7177
[case testRaiseTupleTypeFail]
7278
import typing
7379
x = None # type: typing.Type[typing.Tuple[typing.Any, typing.Any, typing.Any]]
7480
raise x # E: Exception must be derived from BaseException
7581
[builtins_py2 fixtures/exception.pyi]
7682

77-
[case testRaiseTupleOfThreeOnPython2]
78-
from types import TracebackType
79-
from typing import Optional, Tuple, Type
80-
81-
e = None # type: Optional[TracebackType]
82-
83-
raise BaseException # ok
84-
raise BaseException(1) # ok
85-
raise (BaseException,) # ok
86-
raise (BaseException(1),) # ok
87-
raise BaseException, 1 # ok
88-
raise BaseException, 1, e # ok
89-
raise BaseException, 1, None # ok
90-
91-
raise Exception # ok
92-
raise Exception(1) # ok
93-
raise (Exception,) # ok
94-
raise (Exception(1),) # ok
95-
raise Exception, 1 # ok
96-
raise Exception, 1, e # ok
97-
raise Exception, 1, None # ok
98-
99-
raise int, 1 # E: First argument must be BaseException subtype
100-
raise Exception(1), 1 # E: First argument must be BaseException subtype
101-
raise Exception(1), 1, None # E: First argument must be BaseException subtype
102-
raise Exception, 1, 1 # E: Third argument to raise must have "Union[types.TracebackType, None]" type
103-
raise int, 1, 1 # E: First argument must be BaseException subtype \
104-
# E: Third argument to raise must have "Union[types.TracebackType, None]" type
105-
106-
t1 = (BaseException,)
107-
t2 = (Exception(1), 2, 3, 4) # type: Tuple[Exception, int, int, int]
108-
t3 = (Exception,) # type: Tuple[Type[Exception], ...]
109-
t4 = (Exception(1),) # type: Tuple[Exception, ...]
110-
111-
raise t1 # ok
112-
raise t2 # ok
113-
raise t3 # ok
114-
raise t4 # ok
115-
116-
raise t1, 1, None # E: First argument must be BaseException subtype
117-
raise t2, 1 # E: First argument must be BaseException subtype
118-
raise t3, 1, e # E: First argument must be BaseException subtype
119-
raise t4, 1, 1 # E: First argument must be BaseException subtype \
120-
# E: Third argument to raise must have "Union[types.TracebackType, None]" type
121-
122-
w1 = ()
123-
w2 = (1, Exception)
124-
w3 = (1,) # type: Tuple[int, ...]
125-
126-
raise w1 # E: Exception must be derived from BaseException
127-
raise w2 # E: When raising a tuple, first element must by derived from BaseException
128-
raise w3 # E: When raising a tuple, first element must by derived from BaseException
129-
130-
try:
131-
pass
132-
except Exception:
133-
raise # ok
134-
[builtins_py2 fixtures/exception.pyi]
135-
[file types.pyi]
136-
class TracebackType: pass
137-
13883
[case testTryExceptWithTuple]
13984
try:
14085
None

0 commit comments

Comments
 (0)