Reputation: 26647
What is the difference between these two python idioms?
if data is not None:
return data
if data: return data
Upvotes: 8
Views: 9237
Reputation: 177584
The latter will also reject False
, 0
, []
, ()
, {}
, set()
, ''
, and any other value whose __bool__
method returns False, including most empty collections.
The None
value in Python is often used to indicate the lack of a value. It appears automatically when a function does not explicitly return a value.
>>> def f():
... pass
>>> f() is None
True
It’s often used as the default value for optional parameters, as in:
def sort(key=None):
if key is not None:
# do something with the argument
else:
# argument was omitted
If you only used if key:
here, then an argument which evaluated to false would not be considered. Explicitly comparing with is None
is the correct idiom to make this check. See Truth Value Testing.
Upvotes: 16