8

What is the difference between these two python idioms?

if data is not None: return data

if data: return data

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.