tags:

views:

136

answers:

3

Out of three not None test.

if val != None:

if not (val is None):

if val is not None:

Which is preferable, and why?

+4  A: 

Either of the latter two, since val could potentially be of a type that defines __eq__() to return true when passed None.

Ignacio Vazquez-Abrams
That's rather dastardly `__eq__()` behavior, and something I hadn't considered. Good answer for catching a corner case.
gotgenes
+15  A: 
if val is not None:
    # ...

is the Pythonic idiom for testing that a variable is not set to None. This idiom has particular uses in the case of declaring keyword functions with default parameters. is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program, is is the optimal test for this. As Johnsyweb points out, this is discussed in PEP 8 under "Programming Recommendations".

As for why this is preferred to

if not (val is None):
    # ...

this is simply part of the Zen of Python: "Readability counts." Good Python is often close to good pseudocode.

gotgenes
+4  A: 

From, Programming Recommendations, PEP 8:

Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.

Also, beware of writing "if x" when you really mean "if x is not None" -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!

PEP 8 is essential reading for any Python programmer.

Johnsyweb