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


import_contacts

You may also like:

Related Posts

  • Pandas apply function to column
    12 January

    Pandas apply function to column

    Table of ContentsHow do I apply function to column in pandas?Using dataframe.apply() functionUsing lambda function along with the apply() functionUsing dataframe.transform() functionUsing map() functionUsing NumPy.square() function We make use of the Pandas dataframe to store data in an organized and tabular manner. Sometimes there, is a need to apply a function over a specific column […]

  • Copy file Python
    12 January

    How to Copy File in Python?

    Table of ContentsCopy file using the shutil module in PythonCopy file using the copyfileobj() function in PythonCopy file using the copyfile() function in PythonCopy file using the copy() function in PythonCopy file using the copy2() function in PythonCopy file using the operating system command in PythonCopy file using the os module in PythonCopy file using […]

  • What is percent in python
    11 January

    What is % in Python?

    Table of ContentsWhat is % Operator in Python?The % Operator with strings in pythonThe % Operator as a placeholder for variables  in pythonThe % Operator as format specifiers in pythonConclusion In this article, we will cover what is % in Python and what are different ways to use % in Python. In python, there are […]

  • 09 January

    Convert set to String in Python

    Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusion Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to string in Python […]

  • CharAt in Python
    08 January

    CharAt in Python

    Table of ContentsCharAt() in javaAlternative of charAt() in PythonIterate through String and print its character In this tutorial, we will see about CharAt in Python. If you are already well verse in java and might be looking for charAt() alternative in Python, then you are at right place. In Python, you can get character of […]

  • Convert PDF to text in Python
    07 January

    Convert PDF to Text in Python

    Table of ContentsConvert pdf to text using pypdf2Convert pdf to text using PDFminerConclusion Python is a feature-rich programming language. We can perform different operations on files in python using the different modules and libraries. In this article, we will discuss different ways to convert a pdf file to text in python. Convert pdf to text […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.