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.
Related Posts:
- TypeError: ‘NoneType’ object is not iterable in Python
- TypeError: ‘NoneType’ object is not iterable in Python
- Python NoneType object is not callable (beginner)
- Python `if x is not None` or `if not x is None`?
- Why do I get AttributeError: ‘NoneType’ object has no attribute ‘something’?
- TypeError: ‘NoneType’ object is not iterable in Python
- How to “test” NoneType in python?
- What is a ‘NoneType’ object?
- How can I parse a YAML file in Python
- Cannot find module cv2 when using OpenCV
- Maximum and Minimum values for ints
- How is Anaconda related to Python?
- What is the python keyword “with” used for? [duplicate]
- What is the purpose of meshgrid in Python / NumPy?
- PermissionError: [Errno 13] in Python
- How to add to the PYTHONPATH in Windows, so it finds my modules/packages?
- FileNotFoundError: [WinError 2] The system cannot find the file specified:
- Remove all whitespace in a string
- What is a “method” in Python?
- How to generate all permutations of a list?
- Is there a Python equivalent to Ruby’s string interpolation?
- Python Progress Bar
- Most efficient way to find mode in numpy array
- Python error “ImportError: No module named”
- How to groupby based on two columns in pandas?
- How do I append one string to another in Python?
- Python Progress Bar
- How to correct TypeError: Unicode-objects must be encoded before hashing?
- socket.error: [Errno 48] Address already in use
- Python Key Error=0 – Can’t find Dict error in code
- Creating a basic auto clicker in python
- What’s the difference between torch.stack() and torch.cat() functions?
- How to print to stderr in Python?
- proper name for python * operator?
- How to do superscripts and subscripts in Jupyter Notebook?
- How do I unload (reload) a Python module?
- How to exit a loop in Python?
- ImportError: No module named PIL
- Maximum and Minimum values for ints
- LinAlgError: Last 2 dimensions of the array must be square
- How to get data from SNMP with python?
- What does axis in pandas mean?
- What do >> and << mean in Python?
- Dynamically growing a python array when assigning to it
- “OverflowError: Python int too large to convert to C long” on windows but not mac
- Can’t compare naive and aware datetime.now() <= challenge.datetime_end
- List of zeros in python
- How to remove an element from a list by index
- If vs. else if vs. else statements?
- Python conditional assignment operator
- Quoting backslashes in Python string literals
- AttributeError: Can only use .dt accessor with datetimelike values
- Python string class like StringBuilder in C#?
- How do I clear all variables in the middle of a Python script?
- How to tell if tensorflow is using gpu acceleration from inside python shell?
- When to use “while” or “for” in Python
- Normalize columns of pandas data frame
- Normalize columns of pandas data frame
- Python Error: “ValueError: need more than 1 value to unpack”
- Python: can’t assign to literal
- “Initializing” variables in python?
- Equivalent of shell ‘cd’ command to change the working directory?
- What is PEP8’s E128: continuation line under-indented for visual indent?
- PyQt is thread-safe to the same extent that Qt is thread-safe. The Qt docs will tell you which parts of their API are guaranteed to be so, and under what circumstances.
- How to downgrade the installed version of ‘pip’ on windows?
- Where do I get a SECRET_KEY for Flask?
- What does |= (ior) do in Python?
- How can I find the first occurrence of a sub-string in a python string?
- NumPy List Comprehension Syntax
- How to perform bilinear interpolation in Python
- Python socket.error: [Errno 111] Connection refused
- Windows- Pyinstaller Error “failed to execute script ” When App Clicked
- Python: What is the correct MIME type for attaching html file to email
- Linear regression with matplotlib / numpy
- bash: mkvirtualenv: command not found
- Convert a Unicode string to a string in Python (containing extra symbols)python string unicode type-conversion
- Python Django: You’re using the staticfiles app without having set the STATIC_ROOT setting
- sqlite3.OperationalError: unable to open database file
- Object of type ‘map’ has no len() in Python 3
- How to uninstall jupyter
- Python CSV error: line contains NULL byte
- python NameError: name ‘file’ is not defined
- python BeautifulSoup parsing table
- Python Add to dictionary loop
- how to exit a python script in an if statement
- How to add column to numpy array
- OpenCV NoneType object has no attribute shape
- boto3 python 2.7 ImportError: No module named boto3 USER_BASE USER_SITE site packages doesn’t exist
- How to clear Tkinter Canvas?
- Python official installer missing python27.dll
- TypeError: ‘range’ object does not support item assignment
- Convert string to variable name in python
- Generate a random letter in Python
- NameError from Python input() function
- How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?
- Python-like list comprehension in Java
- Syntax highlighting in vim for python
- Python IOError: File not open for reading
- Strange Exception in Tkinter callback
- AttributeError: ‘Series’ object has no attribute ‘split’ error in sending emails