How do I check if a variable exists?
In Python, you can check if a variable exists by using the globals()
or locals()
function to check if the variable is in the global or local namespace, respectively. For example:
if 'my_variable' in globals():
print('my_variable exists in the global namespace')
else:
print('my_variable does not exist in the global namespace')
Watch a video course
Python - The Practical Guide
Alternatively, you can use the globals().get()
or locals().get()
method to check if a variable exists and return its value, or return None
if it does not exist. For example:
value = globals().get('my_variable')
if value is not None:
print(f'my_variable exists in the global namespace and has value {value}')
else:
print('my_variable does not exist in the global namespace')
It's also possible to use the vars()
function to check if a variable exists in the current namespace, which is either the global or local namespace depending on where the function is called.
if 'my_variable' in vars():
print('my_variable exists in the current namespace')
else:
print('my_variable does not exist in the current namespace')
Another way to check if a variable exists is to use the try-except
block.
try:
my_variable
print('my_variable exists')
except NameError:
print('my_variable does not exist')
You can also use the hasattr()
method to check if an object has a certain attribute (variable).
class MyClass:
my_variable = 'some value'
obj = MyClass()
if hasattr(obj, 'my_variable'):
print('obj has my_variable attribute')
else:
print('obj does not have my_variable attribute')