In this Python tutorial, I will explain how to check if the variable exists in Python. We will see different methods that can be used to Python check if a variable is defined. In this process, we will see the need for a Python variable existence check.
When working with Python, it’s common to find ourselves in a situation where we want Python to check if a variable is defined before using it. This is especially important in large projects or scripts where a variable might be defined conditionally.
Variable in Python: In Python, a variable is used to store data that can be used and manipulated throughout a program. A variable provides a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves.
variable_name = value
Global and Local Variables: Variables declared inside a function or block are local to that function or block. Those declared outside are global.
Remember, in Python, everything is an object. When we create a variable, we’re essentially labeling an object, which is stored in a specific memory location.
Why Checking Variable Existence is Important
Two main reasons for Python check if variable exists are:
- Reassign of variable: In Python, reassigning a variable means assigning a new value to a variable that already exists. When you do this, the variable no longer refers to its previous value (unless another variable or structure still holds a reference to it), and instead, it refers to the new value.
- Exceptions occur: Trying to access this non-existent variable will cause a NameError in Python. So, it becomes crucial to verify if a variable exists before using it.
For example:
Case-1: Reassign of variable in Python
To avoid reassigning a variable in a Python code we need to check if the variable is already present or not.
For instance, Imagine we’re tracking the location of a tourist in Python as they visit various landmarks across the country. We have a Python variable landmark_visited that we update in Python as they visit new places:
landmark_visited = "Statue of Liberty, New York"
landmark_visited = "White House, Washington, D.C."
landmark_visited = "Golden Gate Bridge, San Francisco"
landmark_visited = "Waikiki Beach, Honolulu"
print(landmark_visited)
The output is: Only the last value of the variable is the output, others are lost.
Waikiki Beach, Honolulu
We need to verify variable existence in Python before the declaration.
Case-2: Exception occurs while calling a variable in Python
In Python, a NameError is raised when we try to access a variable name that has not been defined or has not been imported into the current namespace. Essentially, it’s Python’s way of telling us that it doesn’t recognize the name we’re trying to use.
For instance, Imagine we’re a Python data analyst at the National Park Service. Our responsibility includes tracking monthly visitor numbers at various National Parks to help with planning resources and understanding tourism trends in Python.
Yellowstone_visitors = 45320
GrandCanyon_visitors = 39210
Yosemite_visitors = 37600
print(GreatSmokyMountains_visitors)
The output is: In this scenario related to U.S. National Parks, the Python analyst tried to access data (visitor count) for a specific park without ensuring the respective variable was defined first. This action led to a NameError when Python couldn’t recognize the variable name being referenced.
Traceback (most recent call last):
File "C:\Users\kumar\PycharmProjects\pythonProject1\main.py", line 5, in <module>
print(GreatSmokyMountains_visitors)
NameError: name 'GreatSmokyMountains_visitors' is not defined
We need to verify variable existence in Python before using the code.
Different Methods to Check if the variable exists in Python
There are five different ways to check if variable exists in Python:
-
if
statement - Using
try
andexcept
- the
globals()
Function - the
locals()
Function - the
dir()
Function
Let’s see them one by one using demonstrative examples
Method-1: How to see if a variable exists Python using if statement
Sometimes we might want to check if a Python variable is not only existing, but also has been assigned a meaningful value (i.e., not None
or some empty structure).
This method is useful for situations where a variable might exist, but it might be None
, an empty list, an empty string, etc. Remember, in Python, structures like empty lists, strings, dictionaries, etc., are considered False
in a boolean context.
For instance, We’re a resident in New York and we’re trying to list down the events we’ll be attending this month. We want to Python conditionally check variable if we’ve added events for this month or if the Python list is empty.
events_this_month = []
if events_this_month:
print(f"You're attending these events: {', '.join(events_this_month)}")
else:
print('You have no events this month.')
The output is: As the ‘events_this_month‘ stores an empty Python list. So, else statement got triggered.
You have no events this month.
This way we can use if conditional statement to check if variable has been defined Python.
Method-2: Python check if variable exists using try and except
In Python, it’s common to use the try and except approach to handle possible errors. This can be used to gracefully manage the error if a variable does not exist.
For instance, Imagine a tourist agency in Florida. Tourists can choose different packages, and not all packages are available every day. If a user opts for the beach_package, the agency can use:
city_tour = "Three cities tour"
adventure_trip = "Trekking"
jungle_package = "Jungle Adventure Day Trip"
def book_package(package_name):
print(f"Successfully booked: {package_name}")
try:
book_package(beach_package)
except NameError:
print("Sorry, the selected package isn't available today.")
The output is:
Sorry, the selected package isn't available today.
This way we can use try and except block for Python to check variable existence.
Method-3: Python check variable before use with the globals() Function
The globals() function in Python returns a dictionary of the current global symbol table, which includes all global variables and hence, helps Python check if variable defined.
For example, We’re compiling a Python list of national parks and their average visitor count.
nationalParks = {"Yellowstone": 4000000, "Yosemite": 3000000}
if 'nationalParks' in globals():
print("National parks data is available!")
else:
print("Data not found.")
The output is:
National parks data is available!
This way we can use the globals() method to check if var exists in Python.
Method-4: Python check if var exists before use with the locals() Function
While globals()
gives us global variables, locals()
provides a Python dictionary of the current namespace. It can be used inside a function to check the existence of a local Python variable.
For instance, Inside a function, we want to check if a local Python variable for ‘Grand Canyon’ visitor count exists.
def parkData():
grandCanyonCount = 5000000
if 'grandCanyonCount' in locals():
print(f"Grand Canyon sees {grandCanyonCount} visitors on average.")
else:
print("Data not available for Grand Canyon.")
parkData()
The output is:
Grand Canyon sees 5000000 visitors on average.
This way we use locals() function in Python to check variable if exists.
Method-5: Python var check if exists using dir() function
The dir()
method returns a list of names in the current local scope or a list of attributes of an object. It’s another way for the Python method to check variable existence.
For instance, We’re verifying the existence of a variable in Python that stores the number of states in the USA.
numberOfStates = 50
if 'numberOfStates' in dir():
print(f"The USA has {numberOfStates} states.")
The output is:
The USA has 50 states.
This way we can use the dir() function to check a variable in Python if present.
Conclusion
In this tutorial, we have seen how to check if the variable exists in Python using different methods like if conditional statement, try and except block, globals(), locals(), or dir() functions with illustrative examples.
Python variable existence check is essential to prevent errors and manage uncertainties in our Python code.
You may also like to read:
- Check if a variable is None in Python
- How to add two variables in Python
- Isidentifier method in String Python
- Variable in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.