Here are four methods to check if a variable exists in Python.
- Using “locals()” function
- Using “globals()” function
- Using “in operator”
- Using the “try/except” method
Method 1: Python locals()
The locals() is a built-in Python function that returns a “dictionary” of the current local symbol table. The local symbol table stores all information needed for the local scope of the program, and this information is accessed using the built-in function locals().
kb = 19
kl = 21
print(locals())
Output
{'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x102c0cca0>,
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'__file__': '/Users/krunallathiya/Desktop/Code/Python/app.py', '__cached__': None,
'kb': 19, 'kl': 21}
Method 2: Python globals()
The globals() is a built-in Python function that returns the dictionary of the current global symbol table. The symbol table contains all the program’s essential information, including classes, methods, and variable names.
kb = 19
kl = 21
def add():
mbb = 11
ans = mbb + kb
globals()['kb'] = ans
print(ans)
add()
Output
30
Method 3: Python in operator
To check if a variable exists in Python, you can use the “in operator” and check inside the “locals()” dictionary.
To check if a global variable exists, you can use the “in operator” and check inside the “globals()” dictionary.
if 'main_var' in locals():
print('Variable exists')
else:
print('Variable does not exist')
Output
Variable does not exist
Method 4: Using try and except block
try:
main_var
print("Variable exists")
except NameError:
print("Error: No value detected")
Output
Error: No value detected
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Thanks for this! I will give that a ago , hopefully my REST endpoint which relies on a global variable being a certain value wont return a 500 if the variable doesnt exist.