Here are 3 ways to check if a variable exists in Python:
- Using locals() for Local Scope
- Using globals() for Global Scope
- Using try-except Block
Method 1: Using locals() for Local Scope
The locals() function returns a dictionary containing the variables defined in the local scope. You can check if a key exists in this dictionary.
Visual Representation
Example
def check_variable_existence():
# Define a local variable
my_variable = 13
# Check if 'my_variable' exists in the local scope of this function
# returns True if it exists, False otherwise
is_my_variable = "my_variable" in locals()
# Print the result
print(is_my_variable)
# Call the function
check_variable_existence()
Output
True
You can also use the dir() function to check if a variable exists in the local scope.
Method 2: Using globals()
The globals() function returns the dictionary of the current global symbol table. This can be used to check for variables defined at the global level.
Visual Representation
Example
# Define a global variable
my_variable = 13
def check_variable_existence():
# Check if 'my_variable' exists in the global scope
is_my_variable = "my_variable" in globals()
# Print the result
print(is_my_variable)
# Call the function
check_variable_existence()
Output
True
Method 3: Using try-except Block
You can attempt to use the variable in a try block and catch a NameError if the variable does not exist.
Example
try:
print(my_variable)
except NameError:
print("my_variable does not exist")
Output
my_variable does not exist
That’s it.
Esportaren
Thanks for this! I will give that a ago , hopefully my REST endpoint which relies on a global variable being a certain value wont return a 500 if the variable doesnt exist.