the expression if (mask1 | mask2) is None:
returns this error
TypeError: unsupported operand type(s) for |: 'int' and 'NoneType'
How can I check if one of the two variables is None
?
the expression if (mask1 | mask2) is None:
returns this error
TypeError: unsupported operand type(s) for |: 'int' and 'NoneType'
How can I check if one of the two variables is None
?
Not as Pythonic but this would also work
a = 1
b = 2
None in (a, b)
>> False
b = None
None in (a, b)
>> True
Update: OP's exception message indicates he is checking integer
vs None
. Equality checks will NOT suffice. Consider mask1 = 0
, mask2 = None
both will fail falsey equality checks.
TypeError: unsupported operand type(s) for |: 'int' and 'NoneType'
If you are testing for identity for an arbitrary number of elements:
any(map(lambda x: x is None, (mask1, mask2, ..., maskN)) # OR operation.
all(map(lambda x: x is None, (mask1, mask2, ..., maskN)) # AND operation.
As user @Jean-François Fabre mentioned get rid of the map
/ lambda
operation:
any(x is None for x in (mask1, mask2, ..., maskN)) # OR
These will all short-circuit because in Python 3 list comprehension will return an iterator that any
can evaluate at each step. Same with map
/ lambda
those operations return iterators as well. So which you prefer is a stylistic choice.
If you only have two conditionals, then the other answers (that use identity checks, not falsey checks) will suffice.
If you need to check for AND (i.e. all the checks are None
):
if all(x is None for x in (mask1, mask2)):
# execute codes
If you need to check for OR (i.e. any of the checks are None
):
if any(x is None for x in (mask1, mask2)):
# execute codes
You might also consider using set
to check:
if {mask1, mask2} == {None}:
# execute codes for when all are None
if {mask1, mask2} > {None}:
# execute codes for when any is None
if {mask1, mask2} - {None}:
# execute codes for when any is not None.