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 in also uses ==, not is, so might fail in the (rather esoteric) case of an object pretending to be __eq__ to NoneTrue / False... ie True in (a, b) will return True. Equivalently False in (0, 1) will return 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.
any but is correct :P using any, map and a lambda seems like a huge overkill for such a simple task. Why not any(val is None for val in list_of_masks_or_explicit_tuple) ? We don't know exactly when OP wants this to be True but it's irrelevant since it can be easily changedany(x is None for x in …)map is evaluated entirely before checking the any (which will short-circuit). But unless noted otherwise we should certainly assume Python 3.map code in Python 3, except syntactically. Which to prefer is purely a matter of preference. It’s definitely not conceptually simpler.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.
None, or only if one isNonebut the other is notNoneNone, but still the accepted answer applies here also