Determine if variable is defined in Python

user102008 picture user102008 · Oct 20, 2009 · Viewed 689.4k times · Source

How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

Answer

Alex Martelli picture Alex Martelli · Oct 20, 2009
try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")