How do I check if a variable exists in Python?. Have you ever face a situation where you need to check whether a variable exists in your Python code? There are different methods to check if a variable exists, a quick method is to use the hasattr()function. It returns a Boolean value, True if the variable exists and False if the variable doesn’t exists. In this article, we will explain multiple methods for tackling this issue.


1. Quick Example – Check if a Variable exists in Python

These are some quick examples that provide a high-level overview of the methods to check if a variable exists in Python. We will discuss them more in detail.

# Quick Examples:
# Method 1: Using the "if-else" Statement
my_var = "some_variable"

# Using the "if" statement
if my_var in locals():
    print(f"'{my_var}' exists.")
    print(f"'{my_var}' does not exist.")

# Method 2: Using the try...except Blocks
    my_var = temp
    print(f"'temp' exists with a value of {my_var}.")
except NameError:
    print("'temp' does not exist.")

# Method 3: Using the hasattr() Function
class SampleClass:
    attribute = 52

myobj = SampleClass()
attribute_to_check = "attribute"

if hasattr(myobj, attribute_to_check):
    print(f"'{attribute_to_check}' exists within the object.")
    print(f"'{attribute_to_check}' does not exist.")

2. Scopes and Variable Declaration

In python, you can declare a variable in different scopes. These scopes define if a python you can access variable or not in a specific block of code. Variables in Python exist within specific scopes, which dictate where and how you can access it.

There are two primary types of variable scopes: global and local.

2.1 Global Scope of a Variable

A variable in the global scope is accessible from anywhere in the Python script, including inside functions. Global variables are typically declared at the top level of a script, outside of any functions.

In the below example, global_var is declared outside the function access_global, making it a global variable. It can be accessed both inside and outside the function.

# Global Score of a Variable explained
global_var = 32

def access_global():
    # Accessing the global variable from within a function
    print("Inside access_global:", global_var)

print("Outside access_global:", global_var)

# Output:
# Inside access_global: 32
# Outside access_global: 32

2.2 Local Scope of a Variable

Variables declared inside a function have a local scope, meaning they are only accessible within that specific function. Python also supports the concept of an enclosing scope, which occurs when a function is defined within another function. Variables in the enclosing scope can be accessed by the inner function.

The inner function cannot modify variables in the enclosing scope without the use of the nonlocal keyword. See the below example:

# Local Scope of a Variable Explained
def outer_function():
    outer_var = 34

    def inner_function():
        # Accessing the variable from the enclosing scope
        print("Inside inner_function:", outer_var)



# Output:
# Inside inner_function: 34

3. hasattr() Function – Check if Class Variable Exists

The hasattr() function in Python is way to check for the existence of attributes or variables within objects or modules. It allows you to check whether a specified attribute or variable exists without raising exceptions.

The hasattr() function takes two arguments: an object and a string representing the attribute or variable name you want to check for.

It returns a Boolean value, indicating whether the attribute exists within the object. If the attribute exists, hasattr() returns True; if not, it returns False.

# Check if a Class variable exists
class MyClass:
    class_variable = 34

sample_object = MyClass()

# Check if an attribute or variable exists within an object
attribute_name = "class_variable"
if hasattr(sample_object, attribute_name):
    value = getattr(sample_object, attribute_name)
    print(f"'{attribute_name}' exists.")
    print(f"'{attribute_name}' does not exist.")

# OUtput:
# 'class_variable' exists.

4. Using Exception Handling to Check if Variable Exists

Another method to check if a variable exists or not in Python is by using try…except blocks. This approach involves attempting to access a variable and handling any resulting exceptions. If the variable does not exist, a NameError exception will be raised.

There is a common saying that it is often “easier to ask forgiveness than permission” when it comes to checking for variable existence. Instead of explicitly checking if a variable exists before using it, Python encourages a “look before you leap” approach, where you attempt to access the variable and handle any exceptions that may arise.

Let’s look into these two methods in detail:

4.1 Look Before You Leap ( LEAP)

When you “look before you leap,” you use the “try…except” blocks to test if a variable exists. By attempting to access the variable and catching exceptions if it doesn’t exist, you can gracefully handle situations where the variable is not present.

In the “look before you leap” approach, you explicitly check if a variable exists before attempting to use it. Here’s an example:

# Using if-else (LEAP) method
my_var = 32

# Check if a variable exists before using it
if 'my_var' in locals():
    result = my_var
    print(f"'my_var' exists .")
    print("'my_var' does not exist.")

# OUtput:
# 'my_var' exists .

4.2 Easier to Ask Forgiveness than Permission

The “easier to ask forgiveness than permission” principle aligns with using try…except blocks for variable existence checks. Instead of checking if a variable exists, you assume it does and handle any exceptions that may occur. This approach can lead to cleaner and more concise code, particularly when dealing with dynamic and unpredictable data.

See the below example of applying the “easier to ask forgiveness than permission” principle to variable existence checks:

# Assume the variable exists and handle the exception if it doesn't
    result = some_variable
    print(f"'some_variable' exists with a value of {result}.")
except NameError:
    print("'some_variable' does not exist.")

# OUtput:
# some_variable' does not exist.

5. Using the globals() and locals() Functions

The globals() and locals() functions allow you to access variables within different scopes. These functions inspect variables within a specific scope, whether it’s the global scope or a local function scope.

5.1 The globals() Function

The globals() function returns a dictionary of the current global symbol table. This dictionary contains all global variables and their values. To check if a variable exists in the global scope, you can use the globals() function and then search for the variable within the returned dictionary.

# The global scope of variable and check if exists
my_var = 34

def check_global_variable(var_name):
    # Use the globals() function to access the global symbol table
    global_symbols = globals()
    if var_name in global_symbols:
        print(f"'{var_name}' exists in the global scope.")
        print(f"'{var_name}' does not exist in the global scope.")

# Check if a variable exists in the global scope

# OUtput:
# 'my_var' exists in the global scope.
# 'non_existent_var' does not exist in the global scope.

5.2 The locals() Function:

The locals() function, similar to globals(), returns a dictionary, but it contains the variables and their values in the current local symbol table. This means you can use it to inspect variables in the local scope.

# Check if variable exists in local socpe
def check_local_variable(var_name):
    # Use the locals() function to access the local symbol table
    local_symbols = locals()
    if var_name in local_symbols:
        print(f"'{var_name}' exists in the local scope.")
        print(f"'{var_name}' does not exist in the local scope.")

def some_function():
    local_number = 99

    # Check if a variable exists in the local scope


Yields the below output:

6. Using the in Operator

For a thorough check, you can also inspect the built-in scope using the in operator. You can apply the in operator to the dictionary returned by vars(__builtins__).

The built-in scope contains Python’s built-in functions, objects, and exceptions, such as print, len, and TypeError. It represents the core functionality of Python.

# Using 'in' operator to check in built-in scope
var_name = "type"
if var_name in vars(__builtins__):
    print(f"'{var_name}' exists in the built-in scope.")
    print(f"'{var_name}' does not exist in the built-in scope.")

# Output:
# 'type' exists in the built-in scope.

7. Summary and Conslusion

n this article, we have explained different approaches to check if a variable exists in python. We have discussed the “Look Before You Leap” and “Easier to Ask Forgiveness Than Permission.” If you have any questions about these methods, please feel free to ask in the comment section below.

Happy Coding!!!

Leave a Reply