How to Check if a Variable Exists in Python
In this article, we will learn to check the existence of variables in Python. We will use some built-in functions in Python and some custom codes including exceptions of the functions as well. Let's first have a quick look over what are variables and then how many types of variables are there in Python.
What is Variable in Python?
Variables are containers and reserved memory locations for storing data values. Variables store data that can be used when evaluating an expression. Variables in Python can store any type of data or value say, integer type, string type, float type, or a boolean value, etc. There is no need to mention the type of the variable while defining it in the program. In the Python programming language, it is necessary for the variables to be defined before they are used in any function or in the program.
Variable Example
x = 3
x is a variable of integer type becuase it holds integer value. No data type like int is used before the variable name.
In Python, all variables are expected to be defined before use. The None object is a value you often assign to signify that you have no real value for a variable, as shown below.
try: x
except NameError: x = None
Then it’s easy to test whether a variable is bound to None or not.
if x is None:
some_fallback_operation( )
else:
some_operation(x)
Python Variable Exist or Not?
Python doesn’t have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if we initially assigned the variable to None object. Attempting to access a variable that hasn’t previously been defined raises a NameError
exception. This NameError exception can be handled with a try/except statement, as you can do for any other Python exception.
We can use try-except
block to check the existence of a variable that is not defined earlier before use.
try:
myVarexcept NameError:
# Do something.
Instead of ensuring that a variable is initialized like we see above that variable was assigned none value, you may prefer to test whether it’s defined where you want to use it. Let us see the example below.
try: x
except NameError: some_fallback_operation( )
else: some_operation(x)
Now, Python brings two functions locals()
and globals()
to overcome this situation. These two functions will help in checking whether the two variables i.e. local variable and global variable exists or not.
Checking Local Variable Existence in Python
To check the existence of a variable locally we are going to use the locals()
function to get the dictionary of the current local symbol table. It returns true if the variable is found in the local entry system else returns false.
def func():
# defining local variable
local_var = 0
# using locals() function for checking existence in symbol table
is_local = "local_var" in locals()
# printing result
print(is_local)
# driver code
func()
TRUE
Checking Global Variable Existence in Python
Now, To check the existence of a variable globally we are going to use the globals()
function to get the dictionary of the current global symbol table.
def func():
# defining variable
global_var = 0
# using globals() function check if global variable exist
is_global = "global_var" in globals()
# printing result
print(is_global)
# driver code
func()
FALSE
This way the programmer can use the locals() and globals() function provided by Python language to check the existence of the variable. The program will print TRUE if the variable exists and FALSE if the variable does not exist.
Conclusion
In this article, we learned to check the existence of variables in Python by using two built-in functions such as locals()
and globals()
. We used some custom codes as well. We learned about exceptions too. For example, we used None object and assigned it to a new variable, and checked what exceptions we are getting using examples.