Determine if variable is defined in Python [duplicate]

Solution 1:

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

Solution 2:

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

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

Solution 3:

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

a = None
if condition:
    a = 42

Solution 4:

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope