Open
Description
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.
Metadata
Metadata
Assignees
Projects
Milestone
Relationships
Development
No branches or pull requests
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==
inNone
tests (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 forlist
anddict
, this will be already helpful for--strict-optional
.JukkaL commentedon Jan 15, 2020
Here's another example reported by @memery-imb in #8279:
Optional
is unpacked withNone not in
. #113391 remaining item