|
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 |
@@ -512,13 +513,22 @@ def unify_generic_callable(type: CallableType, target: CallableType, |
512 | 513 |
|
513 | 514 |
|
514 | 515 | def restrict_subtype_away(t: Type, s: Type) -> Type: |
515 | | - """Return a supertype of (t intersect not s) |
| 516 | + """Return t minus s. |
516 | 517 |
|
517 | | - Currently just remove elements of a union type. |
| 518 | + If we can't determine a precise result, return a supertype of the |
| 519 | + ideal result (just t is a valid result). |
| 520 | +
|
| 521 | + This is used for type inference of runtime type checks such as |
| 522 | + isinstance. |
| 523 | +
|
| 524 | + Currently this just removes elements of a union type. |
518 | 525 | """ |
519 | 526 | if isinstance(t, UnionType): |
520 | | - new_items = [item for item in t.items if (not is_subtype(item, s) |
521 | | - or isinstance(item, AnyType))] |
| 527 | + # Since runtime type checks will ignore type arguments, erase the types. |
| 528 | + erased_s = erase_type(s) |
| 529 | + new_items = [item for item in t.items |
| 530 | + if (not is_proper_subtype(erase_type(item), erased_s) |
| 531 | + or isinstance(item, AnyType))] |
522 | 532 | return UnionType.make_union(new_items) |
523 | 533 | else: |
524 | 534 | return t |
@@ -640,6 +650,9 @@ def visit_tuple_type(self, left: TupleType) -> bool: |
640 | 650 | if not right.args: |
641 | 651 | return False |
642 | 652 | iter_type = right.args[0] |
| 653 | + if is_named_instance(right, 'builtins.tuple') and isinstance(iter_type, AnyType): |
| 654 | + # Special case plain 'tuple' which is needed for isinstance(x, tuple). |
| 655 | + return True |
643 | 656 | return all(is_proper_subtype(li, iter_type) for li in left.items) |
644 | 657 | return is_proper_subtype(left.fallback, right) |
645 | 658 | elif isinstance(right, TupleType): |
|
0 commit comments