How to Check If Variable Exists in Python?

Learn via video course
FREE
View all courses
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Python Course for Beginners With Certification: Mastering the Essentials
Python Course for Beginners With Certification: Mastering the Essentials
by Rahul Janghu
1000
4.90
Start Learning
Topics Covered

Overview

In Python, before we perform an operation on a variable is important to check if a variable exists or not. If this step is avoided, an exception might appears. To avoid such errors, Python offers three explicit ways to check if a variable exists which are explained below making it easier for the developer to check in advance and make its code error less.

Introduction to Check if a Variable Exists in Python

In the below article, we shall check if a variable exists in Python in various ways (including code examples, algorithms, and elaborative explanations), but before that let us briefly discuss what a variable is.

Defining a Variable in Python?

We can define a variable as containers (or reserved memory locations) where the data values are stored and used while evaluating any expression. In Python, the variables have data types like integer type, string type, float type, or a boolean value, etc. It is recommended to always define a variable before utilizing them in any function or program.

Note: You don't need to necessarily mention the data type for the variable while you are defining it in the code.

Code:

Output:

Explanation:

As seen above, we considered two cases, where in the first case we defined the variable 'y' as an int value of 7. We print the variable to check if the value given to the variable gets reflected. No data type like int is used before the variable name. For case two, we explicitly define the datatype as float and the same gets printed as well for the variable 'a' with a float value of 8.0.

As we need to mandatorily define the variable before utilizing it, we often use the 'None' object to specify that we have no real value assigned for the variable as shown in the below code example.

Code:

Output:

Explanation:

As seen above, we can test like above whether a variable is a None object or not.

As we understand what is a variable, let us get back to learning in Python to check if a variable exists or not. Let us answer the question, of why is it necessary in Python, check if a variable exists.

We consider the scenario of not setting or defining the variable explicitly as a bad practice while programming in Python. It is so because this implies that the logic of the code is not appropriately thought out, which in the future leads to giving unpredictable errors or behavior.

In Python, check if a variable exists we use either one of the three methods given below:

  • Python check if a variable exists using a local variable
  • Python check if a variable exists using the global variable
  • Use any variable without being defined or set in Python

We shall use the in operator and check inside the locals() dictionary. Similarly, we can use the in operator and check inside the global() dictionary. We use the try-except block for the undefined variables in Python to check if the variable exists.

Let us discuss each one by one in detail.

Python Check if a Variable Exists Using a Local Variable

Intro:

We define the local() variable as a built-in Python function that returns a dictionary for the current local symbol table. It is this local symbol table, where all the information related to the local scope of the code base is stored. This local() variable can be accessed for the information using the Python built-in function locals().

Sample Code for local() varible:

Output:

We see the three variables we defined as locals printed at the end are all the ones we defined as the above sample code.

Algorithm:

  • In Python, check if the variable exists using the local variable in the three cases we explored.
  • In the first case, we create a user-defined function named check_var_local_case1(), in which we declare the local_var as 22 int data type. We then check if this exists in the locals() variable using the in operator. We then print the variable to check and find that in Python, check if the variable exists.
  • In the second case, we create a user's defined function named check_var_local_case2(), in which we declare the local_var as 33 int data type. We then check if this exists in the locals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is present in a local() variable as in this case.
  • In the third case, we create users defined function named check_var_local_case3(), in which we declare the local_var as 66 int data type. We then check if this exists in the locals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is not present in the local() variable.

Code:

Output:

Explanation:

As seen above, we see three defied cases where we declare a local_var of different int data type values. Then we check one by one in Python, checking if the variable exits using the local() variable. We implement the in operator in the first case and find local() variable exists. While in the second case we use the if-else statement and in-operator to find that the local() variable exists. For the third case we apply the same (if-else statement and in operator ). and find out that the local() variable doesn't exist.

Python Check if the Variable Exists Using a Global Variable

Intro:

We define the global() variable as a built-in Python function that returns a dictionary for the current global symbol table. All the essential data structures that a code base(or program) requires like classes, methods, and variable names are termed symbol tables.

Sample Code for local() variable:

Output:

Explanation:

We see the three variables we defined as globals printed at the end are all the ones we defined as the above sample code. We created the user-defined function where we used the globally defined variable to perform the addition operation. As no errors were thrown, it states that we accessed the global variable inside the user-defined function.

Algorithm:

  • In the first case, we create a user-defined function named check_var_global_case1(), where we have already declared the global_var as a 22 int data type. We then check if this exists in the globals() variable using the in operator. We then print the variable to check and find that in Python, check if a variable exists.
  • In the second case, we create users defined function named check_var_global_case2(), where we have already declared the global_var as 33 int data type. We then check if this exists in the globals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is present in the globals() variable as in this case.
  • In the third case, we create a user's defined function named check_var_global_case3(), where we have already declared the global_var as 66 int data type. We then check if this exists in the globals() variable using the if-else statement and in the operator. If the variable exists, we use the print statement to print the message that it is not present in the globals() variable.

Code:

Output:

Explanation:

As seen above, we see three different cases where we declare a global_var of different int data type values. Then we check one by one in Python, check if a variable exit using the globals() variable. We implement the in operator in the first case and find globals() variable exists. While in the second case we use the if-else statement and in-operator to find that the globals() variable exists. For the third case, we apply the same (if-else statement and in operator) and find out that the globals() variable doesn't exist.

Use Any Variable Without Being Defined or Set in Python

Intro:

In Python, though we don't have a defined function to check and test if a variable is already defined or not, as it is usually believed that all variables have been defined (be it initially assigned to a None object). You might come across a scenario where you may have got a NameError exception while trying to call or access the variable that has not been defined earlier. This NameError exception is efficiently handled using a try/except clause.

We use variables that have not been defined or set in Python, via the try-except statement. If we see that an error is raised, then set the value of that variable to None using the same try-except statement.

Algorithm:

  • In Python, check if a variable exists is properly defined or not, we evaluate this problem statement with two cases.
  • In the first case, we don't define the variable and check if the NameError arises and what is the value of the variable.
  • We use the try-except clause to check the same, as per expectation the NameError exception is raised and we set the value to a None object type to avoid further error exceptions. Hence, it returns None.
  • In the second case, we define the variable as a string data type, and hence when it passes through the try block it prints its value as a string. No NameError exception is raised in this case.

Code:

Output:

Explanation:

We explore two cases in Python, to check if a variable exists and is properly defined or not. In the first case, we don't define the variable and check if the NameError arises and what is the value of the variable. Here we set the value to a None object type to avoid further error exceptions. Hence, it returns None. While in the second case, we define the variable as a string data type, and hence when it passes through the try block it prints its value as a string. No NameError exception is raised in this case.

Conclusion

  • A variable as containers (or reserved memory locations) where the data values are stored and are used while evaluating any expression. In Python, the variables have data types like integer type, string type, float type, or a boolean value, etc.

  • The local() variable is a built-in Python function that returns a dictionary for the current local symbol table. It is this local symbol table, where all the information related to the local scope of the code base is stored. This local() variable can be accessed for the information using the python built-in function locals().

  • The scenario of not setting or defining the variable explicitly is a bad practice while programming in Python. It is so because this implies that the logic of the code is not appropriately thought out, which in the future leads to giving unpredictable errors or behavior.

  • The global() variable is a built-in Python function that returns a dictionary for the current global symbol table. All the essential data structures that a code base(or program ) requires like classes, methods, and variable names are termed a symbol table.