8

What is the difference between these two python idioms?

if data is not None: return data

if data: return data

Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424
  • 1
    See: http://stackoverflow.com/questions/6497166/problem-with-pythons-is-none-test and http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none – Josh Lee Jun 14 '13 at 21:26

1 Answers1

16

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.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275