Skip to content

Support or in isinstance expressions. #942

Closed

Description

@jhance

I saw in some place in mypy something like

class A:
    pass

class B(A):
    pass

class C(A):
    pass

x = C()  # type: A
if isinstance(x, B) or isinstance(x, C):
    y = cast(Union[B, C], x)
    ...

We should be able to infer Union[B, C] as the type of x within this expression.

Activity

  1. JukkaL commented on Oct 17, 2015

    @JukkaL
    Collaborator

    Yes, that would be nice. #947 is related (tuple as the second argument to isinstance).

  2. jhance commented on Oct 18, 2015

    @jhance
    CollaboratorAuthor

    It seems like this can get complex pretty quickly (imagine using tuples inside an and, now you effectively have an intersection of unions). Theres so many cases to cover that I'm thinking about just going all-out here and writing an all-encompassing solution.

    I've been toying with converting the expressions to DNF and seeing if we can just do an all-encompassing solution that way but I'm not confident in its correctness since it effectively makes complicated cases just as difficult as simple cases.

  3. JukkaL commented on Oct 18, 2015

    @JukkaL
    Collaborator

    At this point it's okay to add some limitations, such as for and all the operands must target different variables. So this wouldn't work correctly:

    if isinstance(x, A) and isinstance(x, B): ...
    

    (we'd only recognize the first isinstance, since mypy doesn't support intersection types)

    We can revisit this later, but the complex cases are going to be pretty marginal so it's not worth it to complicate everything because of them.

  4. JukkaL commented on Oct 18, 2015

    @JukkaL
    Collaborator

    In general, if in doubt whether a particular idiom or construct is worth supporting, try to find actual examples of that in some existing projects. If you can't find any (or just find a few isolated examples), it's probably not that important, and there are lot of things that mypy can't deal with that we know to be important (such as every issue tagged with 'priority').

  5. self-assigned this
    on Jun 15, 2016
  6. added 2 commits that reference this issue on Jun 15, 2016
    172ac66
    d025588
  7. added a commit that references this issue on Jun 22, 2016
    56ce18d
  8. added a commit that references this issue on Jun 27, 2016
    32062eb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions