El Dude
El Dude

Reputation: 5618

More pythonic way to test for is none

Which way to test for a variable == None is the more pythonic?

if var:

or

if var is not None

?

I personally would favor the primer. But the latter is more explicit. https://www.python.org/dev/peps/pep-0020/

But for what benefit? Beginner programmers - should this be assumed in production grade software?

Upvotes: 0

Views: 525

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155654

If None-ness is important, and it's possible you'd receive a falsy value that should not be treated equivalently, you have to use is not None. But if you're just testing None vs. "some other value guaranteed to be truthy", then it's really personal preference.

For example, when testing the result of a regex .match call, if matchobj: and if matchobj is not None: are both fine; match returns either None for a failed match or a guaranteed truthy match object, so it's mostly a matter of personal style. if matchobj: is microscopically faster, but not enough to weight the decision meaningfully.

Upvotes: 3

Patrick Artner
Patrick Artner

Reputation: 51683

You check explicitly with if var is not None:

Reason

does_not_work = 0

if does_not_work:
    print("Works - is not none")
else:
    print("Is None ... or not?")

See What is Truthy and Falsy? How is it different from True and False?

The simple test checks for truthyness - not None.

Upvotes: 8

Related Questions