Determine if variable is defined in Python [duplicate] Determine if variable is defined in Python [duplicate] python python

Determine if variable is defined in Python [duplicate]


try:    thevariableexcept NameError:    print("well, it WASN'T defined after all!")else:    print("sure, it was defined.")


'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)


I think it's better to avoid the situation. It's cleaner and clearer to write:

a = Noneif condition:    a = 42