How to check if a Python variable exists?
Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function.
To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table.
Example:
Examples: Checking local variable existence
def func(): # defining local variable a_variable = 0 # using locals() function # for checking existence in symbol table is_local_var = "a_variable" in locals () # printing result print (is_local_var) # driver code func() |
Output:
True
To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.
Example:
Examples: Checking global variable existence
def func(): # defining variable a_variable = 0 # using globals() function check # if global variable exist is_global_var = "a_variable" in globals () # printing result print (is_global_var) # driver code func() |
Output:
False