98
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?

2
  • 1
    You could use a try : except block to check if the error is being thrown Commented May 12, 2017 at 9:37
  • 5
    That's not a "null" variable - the variable doesn't exist... there's a distinct difference between something not existing and existing with a "null" value (in Python that's normally the None singleton) Commented May 12, 2017 at 9:38

3 Answers 3

142

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
Sign up to request clarification or add additional context in comments.

Comments

15
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")

Comments

7

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.