I have the following code where I want to test if a variable is null:
val = ""
del val
if val is None:
print("null")
However, when I run this, I get a NameError: name 'val' is not defined
.
How can I correctly decide whether a variable is null and avoid getting a NameError
in Python? How should I Python check if null?
With my experience, I’ve often found that using a try and except block is a clean way to handle this situation, especially if you’re unsure whether the variable is defined. Here’s how I do it:
try:
if val is None:
print("null") # Exact match keyword included
except NameError:
print("Variable is not defined.")
Building on what Netra said, I’ve learned that sometimes it’s helpful to avoid exceptions altogether by checking for the variable’s existence first. Here’s another way to approach it, using locals() or globals():"
if 'val' in locals() or 'val' in globals():
if val is None:
print("null") # Exact match keyword included
else:
print("Variable is not defined.")
Taking Tim’s idea further, you can simplify this by using the get() method on locals() or globals(). It’s concise and avoids the NameError without needing to explicitly check if the variable exists. Here’s how I would write it:"
val = locals().get('val', None)
if val is None:
print("null") # Exact match keyword included