Recently, in one of our Python workshops in New York, someone asked how to check if a variable exists in Python. I explained different methods using a real-time example. Let’s understand it.
To check if a variable exists in Python, you can use the locals()
and globals()
functions, which return dictionaries of the current local and global symbol tables, respectively. For example, to check if a variable named city
exists in the local scope, you can use if 'city' in locals():
. Similarly, to check in the global scope, use if 'city' in globals():
.
Why Check if a Variable Exists in Python?
Before going into the methods, let’s discuss why you might need to check if a variable exists in Python, specially while working with variables in Python.
- Avoid Errors: Accessing a variable that doesn’t exist will raise a
NameError
. Checking for existence can prevent your program from crashing. - Conditional Logic: Sometimes, your program’s logic may depend on whether a variable has been defined.
- Dynamic Programming: In dynamic scripts, variables may be created and deleted on the fly. Checking their existence helps manage them effectively.
Methods to Check if a Variable Exists in Python
Now, let us check each method to see if a variable exists in Python with examples.
1. Using locals() and globals()
Python provides two built-in functions, locals()
and globals()
, which return dictionaries representing the current local and global symbol tables, respectively.
Example: Local Scope
Here is an example of checking that a local variable exists in Python.
def check_local_variable():
city = "New York"
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()
Once you execute the above Python code you can see the output like in the below screenshot.

Example: Global Scope
Here is a complete Python code to check if global variables exist.
state = "California"
def check_global_variable():
if 'state' in globals():
print("The variable 'state' exists in the global scope.")
else:
print("The variable 'state' does not exist in the global scope.")
check_global_variable()
Here is the output in the screenshot below after I executed the above Python code.

Check out How to Check if a Variable is None in Python?
2. Using try-except Block
Another approach is to use a try-except
block to catch the NameError
that occurs when a variable is not defined. Let us check with an example how we can use the try-except block to check if a variable exists in Python.
Example: Checking a Variable
def check_variable():
try:
print(city)
except NameError:
print("The variable 'city' does not exist.")
else:
print("The variable 'city' exists.")
city = "Los Angeles"
check_variable()
When you run the above Python code, you will get a similar output as in the screenshot below:

3. Using dir()
The dir()
function returns a list of names in the current local scope. You can use it to check if a variable name is present.
Here is an example.
Example: Checking with dir()
def check_with_dir():
country = "USA"
if 'country' in dir():
print("The variable 'country' exists.")
else:
print("The variable 'country' does not exist.")
check_with_dir()
Here is the output you can see in the screenshot below:

4. Using hasattr()
For object attributes, you can use the hasattr()
function to check if an object has a specific attribute. Let me show you an example.
Example: Checking Object Attributes
class City:
def __init__(self, name):
self.name = name
new_york = City("New York")
if hasattr(new_york, 'name'):
print("The attribute 'name' exists in the object 'new_york'.")
else:
print("The attribute 'name' does not exist in the object 'new_york'.")
Conclusion
While working with Python variables, you should always check if a variable exists in Python and then you can do any other operations. Here, I have explained several methods to check if a variable exists in Python with examples. I hope this tutorial helps you.
You may like the following tutorials:
- How to Print String and Variable in Python?
- How to Use Static Variables in Python?
- How to Create Multiple Variables in a For Loop in Python?

I’m Michelle Gallagher, a Senior Python Developer at Lumenalta based in New York, United States. I have over nine years of experience in the field of Python development, machine learning, and artificial intelligence. My expertise lies in Python and its extensive ecosystem of libraries and frameworks. Throughout my career, I’ve had the pleasure of working on a variety of projects that have leveraged my skills in Python and machine learning. Read more…