Skip to content

Strict optional doesn't recognize "None in (...)" tests #2980

Open

Description

@JukkaL

A user reported code which basically boils down to this:

class A:
    a: Optional[int]
    b: Optional[int]
    ...
    def f(self) -> None:
        if None in (self.a, self.b):
            return
        print(self.a + self.b)  # ok at runtime but mypy error currently

Mypy doesn't recognize the None in (...) test as a legitimate None test.

The code seems a little unusual but if we see this frequently enough it might be worth supporting at some point.

Activity

  1. gvanrossum commented on Mar 8, 2017

    @gvanrossum
    Member
  2. refi64 commented on Mar 8, 2017

    @refi64
    Contributor

    FWIW, doesn't this end up basically being self.a == None and self.b == None? I'm not sure if it would be entirely safe, since it runs into the normal issues of using == in None tests (e.g. custom __eq__ overloads).

  3. gvanrossum commented on Mar 8, 2017

    @gvanrossum
    Member

    Sure (with 'or' though), but AFAIK we allow that elsewhere too, so that doesn't concern me.

  4. ilevkivskyi commented on Oct 7, 2017

    @ilevkivskyi
    Member

    There is a similar, but more useful idiom (that is used several times in mypy itself):

    x: Optional[int]
    cont: Container[int]  # note, non-optional content type
    if x in cont:
        reveal_type(x) # this can be only 'int'
  5. ilevkivskyi commented on Oct 7, 2017

    @ilevkivskyi
    Member

    The above is probably only safe for built-in containers, where we know the behavior of __contains__, but if we allow this at least for list and dict, this will be already helpful for --strict-optional.

  6. JukkaL commented on Jan 15, 2020

    @JukkaL
    CollaboratorAuthor

    Here's another example reported by @memery-imb in #8279:

    def mypy_subtract(nulled: bool) -> float:
        if nulled:
            returnable = [None, None]
        else:
            returnable = [1.0, 2.0]
    
        if None in returnable:
            raise Exception
    
        return returnable[0] - returnable[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions