How to test a variable is null in python

Python

Python Problem Overview


val = ""

del val

if val is None:
    print("null")

I ran above code, but got NameError: name 'val' is not defined.

How to decide whether a variable is null, and avoid NameError?

Python Solutions


Solution 1 - Python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

Solution 2 - Python

try:
    if val is None: # The variable
        print('It is None')
except NameError:
    print ("This variable is not defined")
else:
    print ("It is defined and has a value")

Solution 3 - Python

You can do this in a try and catch block:

try:
    if val is None:
        print("null")
except NameError:
    # throw an exception or do something else

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZephyr GuoView Question on Stackoverflow
Solution 1 - PythonŁukasz RogalskiView Answer on Stackoverflow
Solution 2 - PythonLudisposedView Answer on Stackoverflow
Solution 3 - PythoncezarView Answer on Stackoverflow