Skip to content

Commit 56ce18d

Browse files
committed
Support or in isinstance checks
Fixes python#942.
1 parent 9218536 commit 56ce18d

2 files changed

Lines changed: 134 additions & 10 deletions

File tree

‎mypy/checker.py‎

Lines changed: 79 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2388,6 +2388,22 @@ def method_type(self, func: FuncBase) -> FunctionLike:
23882388
return method_type_with_fallback(func, self.named_type('builtins.function'))
23892389

23902390

2391+
# Data structure returned by find_isinstance_check representing
2392+
# information learned from the truth or falsehood of a condition. The
2393+
# dict maps nodes representing expressions like 'a[0].x' to their
2394+
# refined types under the assumption that the condition has a
2395+
# particular truth value. A value of None means that the condition can
2396+
# never have that truth value.
2397+
2398+
# NB: The keys of this dict are nodes in the original source program,
2399+
# which are compared by reference equality--effectively, being *the
2400+
# same* expression of the program, not just two identical expressions
2401+
# (such as two references to the same variable). TODO: it would
2402+
# probably be better to have the dict keyed by the nodes' literal_hash
2403+
# field instead.
2404+
2405+
# NB: This should be `TypeMap = Optional[Dict[Node, Type]]`!
2406+
# But see https://github.com/python/mypy/issues/1637
23912407
TypeMap = Dict[Node, Type]
23922408

23932409

@@ -2396,7 +2412,7 @@ def conditional_type_map(expr: Node,
23962412
proposed_type: Optional[Type],
23972413
*,
23982414
weak: bool = False
2399-
) -> Tuple[Optional[TypeMap], Optional[TypeMap]]:
2415+
) -> Tuple[TypeMap, TypeMap]:
24002416
"""Takes in an expression, the current type of the expression, and a
24012417
proposed type of that expression.
24022418
@@ -2427,20 +2443,54 @@ def is_literal_none(n: Node) -> bool:
24272443
return isinstance(n, NameExpr) and n.fullname == 'builtins.None'
24282444

24292445

2430-
def and_conditional_maps(m1: Optional[TypeMap], m2: Optional[TypeMap]) -> Optional[TypeMap]:
2446+
def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
2447+
"""Calculate what information we can learn from the truth of (e1 and e2)
2448+
in terms of the information that we can learn from the truth of e1 and
2449+
the truth of e2.
2450+
"""
2451+
24312452
if m1 is None or m2 is None:
2432-
# One of the branches can never occur.
2453+
# One of the conditions can never be true.
24332454
return None
2434-
# Both branches are possible; combine the information.
2435-
result = m1.copy()
2436-
result.update(m2)
2455+
# Both conditions can be true; combine the information. Anything
2456+
# we learn from either conditions's truth is valid. If the same
2457+
# expression's type is refined by both conditions, we somewhat
2458+
# arbitrarily give precedence to m2. (In the future, we could use
2459+
# an intersection type.)
2460+
result = m2.copy()
2461+
m2_keys = set(n2.literal_hash for n2 in m2)
2462+
for n1 in m1:
2463+
if n1.literal_hash not in m2_keys:
2464+
result[n1] = m1[n1]
2465+
return result
2466+
2467+
2468+
def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
2469+
"""Calculate what information we can learn from the truth of (e1 or e2)
2470+
in terms of the information that we can learn from the truth of e1 and
2471+
the truth of e2.
2472+
"""
2473+
2474+
if m1 is None:
2475+
return m2
2476+
if m2 is None:
2477+
return m1
2478+
# Both conditions can be true. Combine information about
2479+
# expressions whose type is refined by both conditions. (We do not
2480+
# learn anything about expressions whose type is refined by only
2481+
# one condition.)
2482+
result = {}
2483+
for n1 in m1:
2484+
for n2 in m2:
2485+
if n1.literal_hash == n2.literal_hash:
2486+
result[n1] = UnionType.make_simplified_union([m1[n1], m2[n2]])
24372487
return result
24382488

24392489

24402490
def find_isinstance_check(node: Node,
24412491
type_map: Dict[Node, Type],
24422492
weak: bool=False
2443-
) -> Tuple[Optional[Dict[Node, Type]], Optional[Dict[Node, Type]]]:
2493+
) -> Tuple[TypeMap, TypeMap]:
24442494
"""Find any isinstance checks (within a chain of ands). Includes
24452495
implicit and explicit checks for None.
24462496
@@ -2484,7 +2534,24 @@ def find_isinstance_check(node: Node,
24842534
_, if_vars = conditional_type_map(node, vartype, NoneTyp(), weak=weak)
24852535
return if_vars, {}
24862536
elif isinstance(node, OpExpr) and node.op == 'and':
2487-
left_if_vars, right_else_vars = find_isinstance_check(
2537+
left_if_vars, left_else_vars = find_isinstance_check(
2538+
node.left,
2539+
type_map,
2540+
weak,
2541+
)
2542+
2543+
right_if_vars, right_else_vars = find_isinstance_check(
2544+
node.right,
2545+
type_map,
2546+
weak,
2547+
)
2548+
2549+
# (e1 and e2) is true if both e1 and e2 are true,
2550+
# and false if at least one of e1 and e2 is false.
2551+
return (and_conditional_maps(left_if_vars, right_if_vars),
2552+
or_conditional_maps(left_else_vars, right_else_vars))
2553+
elif isinstance(node, OpExpr) and node.op == 'or':
2554+
left_if_vars, left_else_vars = find_isinstance_check(
24882555
node.left,
24892556
type_map,
24902557
weak,
@@ -2496,8 +2563,10 @@ def find_isinstance_check(node: Node,
24962563
weak,
24972564
)
24982565

2499-
# Make no claim about the types in else
2500-
return and_conditional_maps(left_if_vars, right_if_vars), {}
2566+
# (e1 or e2) is true if at least one of e1 or e2 is true,
2567+
# and false if both e1 and e2 are false.
2568+
return (or_conditional_maps(left_if_vars, right_if_vars),
2569+
and_conditional_maps(left_else_vars, right_else_vars))
25012570
elif isinstance(node, UnaryExpr) and node.op == 'not':
25022571
left, right = find_isinstance_check(node.expr, type_map, weak)
25032572
return right, left

‎test-data/unit/check-isinstance.test‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -806,6 +806,38 @@ def foo(): pass
806806
[out]
807807
main: note: In function "f":
808808

809+
[case testIsinstanceOr1]
810+
from typing import Optional
811+
def f(a: bool, x: object) -> Optional[int]:
812+
if a or not isinstance(x, int):
813+
return None
814+
reveal_type(x) # E: Revealed type is 'builtins.int'
815+
return x
816+
[builtins fixtures/isinstance.py]
817+
[out]
818+
main: note: In function "f":
819+
820+
[case testIsinstanceOr2]
821+
from typing import Optional
822+
def g(a: bool, x: object) -> Optional[int]:
823+
if not isinstance(x, int) or a:
824+
return None
825+
reveal_type(x) # E: Revealed type is 'builtins.int'
826+
return x
827+
[builtins fixtures/isinstance.py]
828+
[out]
829+
main: note: In function "g":
830+
831+
[case testIsinstanceOr3]
832+
from typing import Optional
833+
def h(a: bool, x: object) -> Optional[int]:
834+
if a or isinstance(x, int):
835+
return None
836+
return x # E: Incompatible return value type (got "object", expected "int")
837+
[builtins fixtures/isinstance.py]
838+
[out]
839+
main: note: In function "h":
840+
809841
[case testIsinstanceWithOverlappingUnionType]
810842
from typing import Union
811843
def f(x: Union[float, int]) -> None:
@@ -860,3 +892,26 @@ def f(x: Union[List[int], str]) -> None:
860892
[out]
861893
main: note: In function "f":
862894
main:4: error: "int" not callable
895+
896+
[case testIsinstanceOrIsinstance]
897+
class A: pass
898+
class B(A):
899+
flag = 1
900+
class C(A):
901+
flag = 2
902+
x1 = A()
903+
if isinstance(x1, B) or isinstance(x1, C):
904+
reveal_type(x1) # E: Revealed type is 'Union[__main__.B, __main__.C]'
905+
f = x1.flag # type: int
906+
else:
907+
reveal_type(x1) # E: Revealed type is '__main__.A'
908+
f = 0
909+
x2 = A()
910+
if isinstance(x2, A) or isinstance(x2, C):
911+
reveal_type(x2) # E: Revealed type is '__main__.A'
912+
f = x2.flag # E: "A" has no attribute "flag"
913+
else:
914+
# unreachable
915+
1()
916+
[builtins fixtures/isinstance.py]
917+
[out]

0 commit comments

Comments
 (0)