Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
JukkaL opened this issue Mar 8, 2017 · 6 comments
Open

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

JukkaL opened this issue Mar 8, 2017 · 6 comments

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Mar 8, 2017

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.

@gvanrossum
Copy link
Member

gvanrossum commented Mar 8, 2017 via email

@refi64
Copy link
Contributor

refi64 commented Mar 8, 2017

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).

@gvanrossum
Copy link
Member

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

@ilevkivskyi
Copy link
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'

@ilevkivskyi
Copy link
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.

@JukkaL
Copy link
Collaborator Author

JukkaL commented Jan 15, 2020

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
Projects
None yet
Development

No branches or pull requests

5 participants