How to check if a Python variable exists?
Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a variable exists in Python.
Using try-except block
Try-except block is Python’s preferred method for handling errors. Instead of checking if a variable exists beforehand, you try to access it and catch the NameError that occurs if the variable doesn't exist.
try:
a
except NameError:
print(True)
else:
print(False)
Output
True
Explanation: Try block attempts to access a. If undefined, a NameError triggers the except block, printing True. If defined, the else block prints False, using exception handling instead of locals() or globals().
Using locals()
locals() function returns a dictionary of all local variables inside functions or current scopes. You can use it to check if a variable exists in the local scope.
a=56
if 'a' in locals():
print(True)
else:
print(False)
Output
True
Explanation: This code checks if the variable a exists in the local scope using locals(). If a is defined locally, it prints True otherwise, it prints False. In this case, since a = 56 is defined, it will print True.
Using globals()
If the variable is declared at the module level outside any functions or classes, it resides in the global scope. The globals() function returns a dictionary of global variables, allowing you to check if a variable exists in the global scope.
def fun():
global a
a = 42
fun()
if 'a' in globals():
print(True)
else:
print(False)
Output
True
Explanation: fun() function assigns 42 to a globally using the global keyword. After calling fun(), globals() checks if a exists and it prints True since a is now a global variable.
Combining locals() and globals()
Sometimes, you might not know if a variable is local or global, and you want to check both scopes. By combining both locals() and globals(), you can ensure that you cover all cases.
a = 10
if 'a' in locals() or 'a' in globals():
print(True)
else:
print(False)
Output
True
Explanation: This code checks if the variable a exists either in the local or global scope using locals() and globals(). Since a = 10 is defined in the global scope, it prints True.