Skip to content
Fix Code Error

not None test in Python

March 13, 2021 by Code Error
Posted By: Anonymous

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.

Answered By: Anonymous

Related Articles

  • How to prevent scrolling the whole page?
  • Search match multiple values in single field in…
  • Best way to extract messy HTML tables using BeautifulSoup
  • How to make Lodash orderBy to sort only the records with…
  • What is the copy-and-swap idiom?
  • Can a "User Assigned Managed Identity" be used locally?
  • OpenIddict Roles/Policy returns 403 Forbidden
  • JavaScript unit test tools for TDD
  • Vue custom directive uses the updated Dom (or $el)
  • How should a model be structured in MVC?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to convert an int to string in C?

Next Post:

(Built-in) way in JavaScript to check if a string is a valid number

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error