HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

What is the best "not None" test in Python

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
thepythonnonetestnotbestwhat

Problem

Out of these not None tests.

if val != None:

if not (val is None):

if val is not None:


Which one is preferable, and why?

Solution

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.

Code Snippets

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

Context

Stack Overflow Q#3965104, score: 1364

Revisions (0)

No revisions yet.