How to Check if a Variable Exists in Python

While reviewing a large Python project for one of my clients in the USA, I encountered a tricky issue: a variable was being used before it was defined. This caused a NameError and broke the entire script.

As a Python developer, I’ve learned that checking whether a variable exists before using it can save you from hours of debugging. Unfortunately, Python doesn’t have a built-in “exists” function for variables, but there are several simple ways to handle this.

In this tutorial, I’ll show you how to check if a variable exists in Python using different methods. I’ll also share practical examples that you can use immediately in your own Python projects.

Method 1 – Use the locals() Function

When I’m working with functions or local code blocks, I often use the locals() function to check if a variable exists.

The locals() function returns a dictionary of all local variables in the current scope. By checking if a variable name exists as a key in that dictionary, we can confirm whether it’s defined.

Here’s how you can do it:

def check_local_variable():
    city = "New York"  # defining a local variable
    if 'city' in locals():
        print("The variable 'city' exists in the local scope.")
    else:
        print("The variable 'city' does not exist in the local scope.")

check_local_variable()

You can refer to the screenshot below to see the output.

python check if variable exists

In this example, since we defined city inside the function, it exists in the local scope. If you remove the line where city is defined, the output will tell you that it doesn’t exist.

This method is perfect when working inside functions or loops where variable definitions might vary depending on conditions.

Method 2 – Use the globals() Function

When working on larger Python scripts or modules, I often define variables at the global level. In such cases, I use the globals() function to check if a variable exists.

The globals() function returns a dictionary containing all global variables and their values. You can easily check for a variable’s existence using the variable name as a key.

Here’s a complete example:

country = "United States"  # global variable

if 'country' in globals():
    print("The variable 'country' exists in the global scope.")
else:
    print("The variable 'country' does not exist in the global scope.")

You can refer to the screenshot below to see the output.

python if variable exists

This method works great when you’re managing configuration variables, constants, or global settings in your Python application.

If you’re developing a Flask or Django app, this approach can help you verify whether global configuration variables are initialized properly before use.

Method 3 – Use try-except Blocks

Sometimes, I prefer a more direct approach. Instead of checking dictionaries, I simply try to use the variable and catch the NameError if it doesn’t exist.

This is one of the most Pythonic ways to handle undefined variables since Python encourages “EAFP”, Easier to Ask for Forgiveness than Permission.

Here’s how you can do it:

try:
    print(user_name)
except NameError:
    print("The variable 'user_name' does not exist.")
else:
    print("The variable 'user_name' exists and its value is:", user_name)

You can refer to the screenshot below to see the output.

check if variable exists python

In this example, if user_name hasn’t been defined yet, Python raises a NameError, which we catch gracefully.

I use this approach frequently in data-processing scripts where variable initialization depends on conditional logic or user input.

Method 4 – Use the dir() Function

Another handy method is using the dir() function, which returns a list of all variable names in the current scope.

This approach is particularly useful when you want to explore what variables currently exist in your environment, for example, during debugging or interactive Python sessions.

Here’s a simple example:

state = "California"

if 'state' in dir():
    print("The variable 'state' exists.")
else:
    print("The variable 'state' does not exist.")

You can refer to the screenshot below to see the output.

python check if class variable exists

This method is quick and readable. However, it’s best suited for interactive or exploratory work, not for production code.

Method 5 – Combine locals() and globals()

In some cases, you may want to check both local and global scopes. For instance, in a large Python script, a variable might be defined globally but accessed inside a function.

To handle both possibilities, you can combine locals() and globals() checks.

Here’s a full working example:

language = "Python"

def check_variable(name):
    if name in locals() or name in globals():
        print(f"The variable '{name}' exists.")
    else:
        print(f"The variable '{name}' does not exist.")

check_variable('language')
check_variable('framework')

This method ensures that you don’t miss variables defined outside the current function. It’s especially helpful when dealing with imported modules or shared configuration files.

Method 6 – Use vars() Function in Python

The vars() function works similarly to locals() and globals(), but it’s often used to inspect objects, modules, or classes. If you’re checking for attributes or variables within a class, vars() can be very handy.

Here’s how I use it in object-oriented Python code:

class Employee:
    def __init__(self):
        self.name = "John Doe"
        self.department = "Finance"

emp = Employee()

if 'department' in vars(emp):
    print("The attribute 'department' exists in the Employee object.")
else:
    print("The attribute 'department' does not exist.")

I use this method a lot when working with dynamic data models or APIs where the available attributes can vary depending on the data source.

Method 7 – Use hasattr() for Object Variables

When dealing with Python classes and objects, the hasattr() function is the easiest way to check if an attribute exists.

Here’s an example:

# Example: Check if an attribute exists using hasattr()

class Car:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

my_car = Car("Ford", 2024)

if hasattr(my_car, 'brand'):
    print("The attribute 'brand' exists in the Car object.")
else:
    print("The attribute 'brand' does not exist.")

This method is clean, efficient, and widely used in professional Python applications. If you’re building APIs or working with JSON data, hasattr() helps you verify the presence of attributes before accessing them, preventing unwanted runtime errors.

Bonus Tip – Avoid NameError in Python

One of the best practices I follow is initializing all variables with default values. This ensures that even if a variable isn’t explicitly set, it won’t cause a NameError.

Here’s a quick example:

# Example: Avoid NameError by initializing variables

user_age = None

if user_age is not None:
    print("User age is:", user_age)
else:
    print("User age is not defined yet.")

This approach improves code readability and prevents unexpected crashes, especially in production environments.

Conclusion

Checking if a variable exists in Python is a small but essential skill that can help you write more reliable and error-free code.

We explored multiple methods, from using locals() and globals() to try-except, dir(), and hasattr(). Each method has its own use case, and the right choice depends on your project’s structure and coding style.

Personally, I rely on try-except for quick checks and hasattr() when working with classes. For debugging and inspection, I often use dir() or vars().

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.