Table of Contents
Introduction
Objective: This article will discuss the different methods to check if a variable exists in Python.
Before we dive into the methods to check for the availability of a variable in the code, let us first understand why we need to do so? 🤔
To answer the above question, you must understand “what is a NameError
and an UnboundLocalError
in Python?“
🐞 NameError and UnboundLocalError in Python
📌 In Python, if you try to access or interact with a variable name that is not defined, you get NameError: name 'variable_name' is not defined
exception.
Example:
1 2 3 4 5 6 7 8 |
numbers = [30,40,25,70,50,35] num=40 for x in numbers: if x > num: add_up += 1 print(add_up) |
Output:
Traceback (most recent call last):
File “main.py”, line 5, in
add_up += 1
NameError: name ‘add_up’ is not defined
❖ Since the variable with name ‘add_up’ is not defined in our code in the above example, we got a NameError
.
📌 Similarly, you get UnboundLocalError: local variable 'variable_name' referenced before assignment
exception when you refer a local variable before assigning it in your program.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Program to find the average of a number def total(num): l = len(num) for x in num: avg += x / l return avg numbers = [30, 10, 60, 20] print('Average = ', total(numbers)) |
Output:
Traceback (most recent call last):
File “main.py”, line 10, in
print(‘Average = ‘, total(numbers))
File “main.py”, line 5, in total
avg += x / l
UnboundLocalError: local variable ‘avg’ referenced before assignment
❖ We got UnboundLocalError
exception because the local variable with the name ‘avg’ was referenced before being assigned in the program.
⚡ Thus, the aforementioned exceptions occur primarily due to the following reasons:-
➥ If you forget to define a variable.
➥ If you use the wrong variable name.
➥ Or if you try to access a variable before defining it.
Both of these errors are pretty common, especially for newbies. To fix them, you can simply edit your program and manually define the variable that leads to the occurrence of these errors.
However, if your code is quite lengthy, then it can be extremely tedious to spot every undefined variable one by one in your program. This is where you can check if a variable exists in the first place before using it.
Read Here: [Solved] ValueError: could not convert string to float
Hence, without further delay, let us discuss the methods to check if a variable exists in the Python code.
✨ Method 1: Using locals() and globals()
locals()
and globals()
are built-in functions in Python that can be used to check for the availability of an identifier. Both these functions return the local and global symbol table, respectively. Thus, you can simply check if a variable exists locally or globally using the respective symbol tables.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
a = 0 def check(): c = 0 if 'a' in globals(): # checking for variable named 'a' in global variables print(True) if 'b' in locals(): # checking for 'b' in local variables print(True) else: print(False) if 'c' in locals(): print(True) check() |
Output:
True
False
True
✨ Method 2: Using dir({object})
dir({object})
is a built-in method in Python that returns the list of methods and attributes of the specified object.
Solution: Let’s incorporate the dir()
method to fix the NameError
in the example mentioned previously.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
numbers = [30, 40, 25, 70, 50, 35] num = 40 for x in numbers: if x > num: if 'add_up' in dir(): # checking for variable in list of names add_up += 1 else: add_up = 1 print("No. of values > {} = {}".format(num, add_up)) |
Output:
No. of values > 40 = 2
✨ Method 3: Using try and except Block
The try
and except
blocks are one of the most effective solutions when you have to deal with exception handling in Python. You can implement the error code in the try block and handle it in the except block.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def total(num): l = len(num) for x in num: try: avg += x / l # error code except: avg = x / l # exception handling code return avg numbers = [30, 10, 60, 20] print('Average = ', total(numbers)) |
Output:
Average = 30.0
✨ Method 4: Using vars([object])
vars()
is another built-in method in Python that returns the__dict_
_ attribute for a module, class, instance, or any other object with a __dict__ attribute. Here,__dict__
refers to the dictionary that stores an object’s (writable) attribute.- Without any arguments, the
vars()
acts just likelocals()
method and returns a dictionary of the current namespace.
Solution: Let’s implement this method to fix the UnboundLocalError
in the example mentioned previously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
def total(num): l = len(num) for x in num: if 'avg' in vars(): # checking for 'avg' in __dict__ using vars() method avg += x / l else: avg = x / l return avg numbers = [30, 10, 60, 20] print('Average = ', total(numbers)) |
Output:
Average = 30.0
❖ __dict__
You can also directly check for a variable using the __dict__
attribute of class or module, or instance.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Checking for existing variables in a class named Variables class Variables(): def __init__(self, a): self.a = a self.check() def check(self): if 'a' in self.__dict__: # accessing __dict__ with class object print('a =', self.a) else: print("'a' is not defined") if 'b' in self.__dict__: print('b =', self.b) else: print("b is not defined") obj = Variables(1) |
Output:
a = 1
b is not defined
Thus, we were able to check for the existence of multiple variables using __dict__
in our example given above.
Conclusion
Let us recall the key points that were discussed in this article:
✔️ NameError
and UnboundLocalError
✔️ Methods to check if a variable exists and resolve the above errors.
Please subscribe and stay tuned for more discussions and solutions in the future.
Authors:
👨🎓 ANIRBAN CHATTERJEE
👨🎓 SHUBHAM SAYON