You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Strict optional doesn't recognize "None in (...)" tests #2980
A user reported code which basically boils down to this:
classA:
a: Optional[int]
b: Optional[int]
...
deff(self) ->None:
ifNonein (self.a, self.b):
returnprint(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.
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).
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.
Activity
gvanrossum commentedon Mar 8, 2017
refi64 commentedon 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==inNonetests (e.g. custom__eq__overloads).gvanrossum commentedon Mar 8, 2017
Sure (with 'or' though), but AFAIK we allow that elsewhere too, so that doesn't concern me.
ilevkivskyi commentedon Oct 7, 2017
There is a similar, but more useful idiom (that is used several times in mypy itself):
ilevkivskyi commentedon Oct 7, 2017
The above is probably only safe for built-in containers, where we know the behavior of
__contains__, but if we allow this at least forlistanddict, this will be already helpful for--strict-optional.JukkaL commentedon Jan 15, 2020
Here's another example reported by @memery-imb in #8279: