Open In App

How to check if a Python variable exists?

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a variable exists in Python.

Using try-except block

Try-except block is Python’s preferred method for handling errors. Instead of checking if a variable exists beforehand, you try to access it and catch the NameError that occurs if the variable doesn't exist.

Python
try:
    a
except NameError:
    print(True)
else:
    print(False)

Output
True

Explanation: Try block attempts to access a. If undefined, a NameError triggers the except block, printing True. If defined, the else block prints False, using exception handling instead of locals() or globals().

Using locals()

locals() function returns a dictionary of all local variables inside functions or current scopes. You can use it to check if a variable exists in the local scope.

Python
a=56

if 'a' in locals():
    print(True)
else:
    print(False)

Output
True

Explanation: This code checks if the variable a exists in the local scope using locals(). If a is defined locally, it prints True otherwise, it prints False. In this case, since a = 56 is defined, it will print True.

Using globals()

If the variable is declared at the module level outside any functions or classes, it resides in the global scope. The globals() function returns a dictionary of global variables, allowing you to check if a variable exists in the global scope.

Python
def fun():
    global a
    a = 42 

fun()

if 'a' in globals():
    print(True)
else:
    print(False)

Output
True

Explanation: fun() function assigns 42 to a globally using the global keyword. After calling fun(), globals() checks if a exists and it prints True since a is now a global variable.

Combining locals() and globals()

Sometimes, you might not know if a variable is local or global, and you want to check both scopes. By combining both locals() and globals(), you can ensure that you cover all cases.

Python
a = 10 

if 'a' in locals() or 'a' in globals():
    print(True)
else:
    print(False)

Output
True

Explanation: This code checks if the variable a exists either in the local or global scope using locals() and globals(). Since a = 10 is defined in the global scope, it prints True.


Next Article

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy