How to check if variable exists in Python

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:

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:

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:

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.

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:

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 like locals() method and returns a dictionary of the current namespace.

Solution: Let’s implement this method to fix the UnboundLocalError in the example mentioned previously.

Output:

Average = 30.0

__dict__

You can also directly check for a variable using the __dict__ attribute of class or module, or instance.

Example:

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

Was this post helpful?

Leave a Reply

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