Skip to content

Commit d177d6c

Browse files
committed
Fix mypy_mypyc crash caused by "complex" interaction
The type of Num.n is `complex`, though it can in practice also be an `int` or a `float`, and we case on the actual type to determine which sort of mypy ast node to use. In #6114, promotions were disabled in `isinstance` checks, which caused mypy to decide that the `isinstance` checks for int and float won't match. Fix this by giving the value the type object instead of complex. Typeshed *does* actually annotate `n` as `Union[float, int, complex]`, but mypy simplifies that into `complex`. (It does *not* do this simplification for local variables with such an annotation; see issue #6168.)
1 parent 3815cbf commit d177d6c

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

mypy/fastparse.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -928,7 +928,11 @@ def visit_Call(self, n: Call) -> CallExpr:
928928

929929
# Num(object n) -- a number as a PyObject.
930930
def visit_Num(self, n: ast3.Num) -> Union[IntExpr, FloatExpr, ComplexExpr]:
931-
val = n.n
931+
# The n field has the type complex, but complex isn't *really*
932+
# a parent of int and float, and this causes isinstance below
933+
# to think that the complex branch is always picked. Avoid
934+
# this by throwing away the type.
935+
val = n.n # type: object
932936
if isinstance(val, int):
933937
e = IntExpr(val) # type: Union[IntExpr, FloatExpr, ComplexExpr]
934938
elif isinstance(val, float):

mypy/fastparse2.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -902,7 +902,11 @@ def visit_Call(self, n: Call) -> CallExpr:
902902

903903
# Num(object n) -- a number as a PyObject.
904904
def visit_Num(self, n: ast27.Num) -> Expression:
905-
value = n.n
905+
# The n field has the type complex, but complex isn't *really*
906+
# a parent of int and float, and this causes isinstance below
907+
# to think that the complex branch is always picked. Avoid
908+
# this by throwing away the type.
909+
value = n.n # type: object
906910
is_inverse = False
907911
if str(n.n).startswith('-'): # Hackish because of complex.
908912
value = -n.n

0 commit comments

Comments
 (0)