How to Check if a Variable Exists in Python?

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.

  1. Avoid Errors: Accessing a variable that doesn’t exist will raise a NameError. Checking for existence can prevent your program from crashing.
  2. Conditional Logic: Sometimes, your program’s logic may depend on whether a variable has been defined.
  3. 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.

Check if a Variable Exists in Python

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.

Python Check if a Variable Exists

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:

How to Check if a Variable Exists in Python

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:

Check if a Variable Exists in Python using different methods

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:

Leave a Comment