|
7 | 7 | ) |
8 | 8 | import mypy.applytype |
9 | 9 | import mypy.constraints |
| 10 | +from mypy.erasetype import erase_type |
10 | 11 | # Circular import; done in the function instead. |
11 | 12 | # import mypy.solve |
12 | 13 | from mypy import messages, sametypes |
@@ -496,13 +497,22 @@ def unify_generic_callable(type: CallableType, target: CallableType, |
496 | 497 |
|
497 | 498 |
|
498 | 499 | def restrict_subtype_away(t: Type, s: Type) -> Type: |
499 | | - """Return a supertype of (t intersect not s) |
| 500 | + """Return t minus s. |
500 | 501 |
|
501 | | - Currently just remove elements of a union type. |
| 502 | + If we can't determine a precise result, return a supertype of the |
| 503 | + ideal result (just t is a valid result). |
| 504 | +
|
| 505 | + This is used for type inference of runtime type checks such as |
| 506 | + isinstance. |
| 507 | +
|
| 508 | + Currently this just removes elements of a union type. |
502 | 509 | """ |
503 | 510 | if isinstance(t, UnionType): |
504 | | - new_items = [item for item in t.items if (not is_subtype(item, s) |
505 | | - or isinstance(item, AnyType))] |
| 511 | + # Since runtime type checks will ignore type arguments, erase the types. |
| 512 | + erased_s = erase_type(s) |
| 513 | + new_items = [item for item in t.items |
| 514 | + if (not is_proper_subtype(erase_type(item), erased_s) |
| 515 | + or isinstance(item, AnyType))] |
506 | 516 | return UnionType.make_union(new_items) |
507 | 517 | else: |
508 | 518 | return t |
@@ -624,6 +634,9 @@ def visit_tuple_type(self, left: TupleType) -> bool: |
624 | 634 | if not right.args: |
625 | 635 | return False |
626 | 636 | iter_type = right.args[0] |
| 637 | + if is_named_instance(right, 'builtins.tuple') and isinstance(iter_type, AnyType): |
| 638 | + # Special case plain 'tuple' which is needed for isinstance(x, tuple). |
| 639 | + return True |
627 | 640 | return all(is_proper_subtype(li, iter_type) for li in left.items) |
628 | 641 | return is_proper_subtype(left.fallback, right) |
629 | 642 | elif isinstance(right, TupleType): |
|
0 commit comments