W3docs

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.

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:

Check if a variable exists in the global namespace in Python

if 'my_variable' in globals():
    print('my_variable exists in the global namespace')
else:
    print('my_variable does not exist in the global namespace')

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

Alternatively, you can use the globals().get() or locals().get() method to retrieve a variable's value. To safely check for existence first, use the in operator:

Check if a variable exists in the global namespace in Python by the get method

if 'my_variable' in globals():
    value = globals().get('my_variable')
    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.

Check if a variable exists in the current namespace in Python

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.

Check if a variable exists in Python in a try-except block

try:
    my_variable
    print('my_variable exists')
except NameError:
    print('my_variable does not exist')

Python favors the EAFP (Easier to Ask for Forgiveness than Permission) style, so using a try-except block is generally preferred over explicit existence checks.

You can also use the hasattr() method to check if an object has a certain attribute.

Check if an object has a certain attribute in Python

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')

Note that hasattr() checks for object attributes, not variables in the local or global namespace.