How to check if variable exists python

To find if variable exists one need to check both local and global scopes but running

if 'my_var' in vars():...


if 'my_var' in globals():...

Below is nicely formated one line of python 3 code checking both and printing out the result.

print('It is {:s} that "a" exists as variable.'.format(str('a' in vars() or 'a' in globals()).lower()))
  • Note that vars() and globals() are built in and does not require any modules to work.