How to Check If Variable Exists in Python

Here are four methods to check if a variable exists in Python.

  1. Using “locals()” function
  2. Using “globals()” function
  3. Using “in operator”
  4. 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 ifvariable 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.

1 thought on “How to Check If Variable Exists in Python”

  1. 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.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.