0

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?

El Dude
  • 5,328
  • 11
  • 54
  • 101
  • 1
    Those aren't equivalent statements at all. `if var:` will skip execution for many values other than `None` - zeros of any numeric type, and empty strings or sequences. – jasonharper Jun 01 '20 at 19:09

2 Answers2

7

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    Python's philosophy is *"Explicit is better than implicit"*, so this is pretty much as pythonic as it gets. – r.ook Jun 01 '20 at 19:09
  • Ah hell, yes. This is the issue if you do not type the variables. In my case I'm looking at a `datetime` that can be None if some `try except` fails. Note to self - do not mix working on static typed languages and python. – El Dude Jun 01 '20 at 19:10
  • @r.ook `if some_variable:` is fine if it's what you mean. – Steven Rumbalski Jun 01 '20 at 19:11
  • @StevenRumbalski It is absolutely fine - provided the `bool` value is what you're testing for. There are definitely use cases for the short form `if some_var:`, but in OP's case, explicit test of `is not None` will probably be more beneficial. – r.ook Jun 01 '20 at 19:11
  • @El there is no "Falsy" DateTime object, so you would be fine using either. but for integers, strings, lists etc. there are falsy evaluated ones, so don`t use it there if you need to distinguish them as None from them as Falsy. – Patrick Artner Jun 01 '20 at 19:14
  • Exactly that was the reason why I asked bc either works in my case. – El Dude Jun 01 '20 at 19:18
3

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.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • My above question arose out of the first situation you mention, it's error handling for a datetime var that has to be set or if something fails is None. – El Dude Jun 01 '20 at 19:13