Method 2: Use the two built-in functions locals() and globals().
locals() : Dictionary-based way to access local variables. The keys are variable names and the values are variable values. globals() : Dictionary-based way to access global variables. The keys are variable names and the values are variable values.
var_exists = 'var' in locals() or 'var' in globals()
Reference article: Several classic questions on the road to learning Python
Python determines whether a variable exists
locals()
: Dictionary-based way to access local variables. The keys are variable names and the values are variable values.globals()
: Dictionary-based way to access global variables. The keys are variable names and the values are variable values.