How do I check if a variable is defined in Python?
Davide S
davide s profile pic

In Python, you can check if a variable is defined using theglobals() orlocals() functions in combination with thein operator. By examining the global and local namespaces, you can determine if a variable has been defined. Here's an example of how you can perform this check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

def is_variable_defined(var_name):
    if var_name in globals() or var_name in locals():
   return True
    else:
   return False

# Usage:
my_var = 10

if is_variable_defined("my_var"):
    print("The variable is defined.")
else:
    print("The variable is not defined.")

In the above code, theis_variable_defined() function takes avar_name parameter representing the name of the variable to check. It checks if the variable name exists in the global namespace (globals()) or the local namespace (locals()) using thein operator. If the variable name is found in either the global or local namespace, it means the variable is defined, and the function returnsTrue. Otherwise, it returnsFalse. You can use theis_variable_defined() function by providing the name of the variable you want to check. It will determine if the variable is defined by searching in the global and local namespaces using theglobals() andlocals() functions. The result is then printed accordingly. It's important to note that theglobals() function provides access to the global namespace, whereas thelocals() function provides access to the local namespace within a specific context, such as a function or method.