How to Check if Variable is Defined in Python

Every Python program heavily relies on variables to store data. If these variables have not been defined when you access them, then your program will give error and may even stop running. In order to avoid such situations, it is important to check if variable is defined in Python, before you use it. Then you can define ways to gracefully deal with situations where undefined variables are accessed.

How to Check if Variable is Defined in Python

Here are the different ways to check if a variable exists in Python program.

1. Using try-except

By default, when you try to access a variable that has not been defined, such as variable ‘a’, you will get a NameError as shown below.

NameError: name 'a' is not defined

In Python, you can catch all such errors and exceptions by wrapping the code in a try-except block.

try:
print(a)
except NameError:
print("a is not defined")
else:
print("a is defined")

In the above code, we have written the print() function inside try block. If the variable a is not defined, then this statement will throw an exception. In this case, the except block will catch it and display ‘a is not defined’. On the other hand, if the variable is indeed defined then it will directly execute the last statement and display ‘a is defined’.

Using try-except block is a very good and recommended way to catch all kinds of errors and handle them effectively.

2. Using global()

Every Python program or script supports a built-in function called globals() that returns a dictionary of all the global variables defined in the program. You can use it to check if a variable is defined globally or not.

a = 24
if 'a' in globals():
print("'a' is defined globally")
else:
print("'a' is not defined globally")

## output
'a' is defined globally

Here is what the output of globals() looks like.

{'__name__': '__main__', ..., 'a': 24}

In the above code, we use ‘in’ clause to check if variable ‘a’ is present in the output of globals(). If the variable is defined globally in your code, then it will be present as a key-value pair in the output. Please note, we have enclosed the variable name in single quotes (‘a’). If you do not use quotes, then it will not work properly.

a = 24
if a in globals():
print("'a' is defined globally")
else:
print("'a' is not defined globally")

## output
'a' is not defined globally

Also, the output of globals() will not contain any local variables. So if you check for the existence of a local variable here, it will fail.

a = 24

def abc():
b=10
if 'b' in globals():
print("'a' is defined globally")
else:
print("'a' is not defined globally")

abc()

## output

'a' is not defined globally

If you need to check if a variable is locally defined or not, you need to use locals() function as described below.

3. Using local()

If you want to check for the presence of a local variable, then you can use locals() function. It returns an dictionary of all local variables. We use the same logic we used earlier to check for global variables.

a = 24

def abc():
b=10
if 'b' in locals():
print("'b' is defined locally")
else:
print("'b' is not defined locally")

abc()

In the above function, we define local variable ‘b’ and check if it is present in the result of locals() function, using ‘in’ clause.

4. Using hasattr

So far, all the examples we have seen are about simple variables in Python. What if you want to check if a specific class attribute is defined or not? In this case, you can use hasattr() function. The hasattr() function is used to check if an object has a specific attribute or not in Python. Here is its syntax.

hasattr(object, attribute)

hasattr() function accepts two arguments – name of object and the name of attribute. It returns true if the attribute is present in object, else it returns false. Here is an example to demonstrate it.

class my_class:
def __init__(self):
self.test = "value"

obj = my_class()

if hasattr(obj, 'test'):
print("test is defined in obj")
else:
print("test is not defined in obj")

## output

attribute is defined in obj

In the above code, we have defined a class my_class. This class has an attribute test. We create an object obj using this class. Then we call hasattr() function, that accepts two arguments. The first argument is the name of object and the second attribute is the name of the attribute.

5. Using None

In this solution, you can set a variable to None beforehand and then check to see if the variable is None or not. This is useful if you want to differentiate between a variable that has been explicitly set to None, and one that has not been defined at all.

a=None

if a is None:
print("a is None")
else:
print("a is defined")

## output
a is None

This solution will help you prevent errors and exceptions.

Conclusion

In this article, we have learnt how to check if a variable is defined or not. You can use try-except block to catch errors in any block of code, including ‘variable not defined’ ones. If you want to check if a variable is defined as a global variable or not, use globals() function. If you want to check if a variable is defined as a local variable or not, use locals() function.

Also read:

How to Reverse String in Python
How to Compare Strings in Python
How to Remove Characters from String

Leave a Reply

Your email address will not be published. Required fields are marked *