
Just wrap what you’re doing in a short try/except clause. Simple. Now you can tell if “variable” is defined without dying in a fire.
try:
x = variable
del x
print "%s is defined" % variable
except NameError:
print "%s is not defined" % variable
Too bad you can’t wrap this in a function definition. Well, you can - sort of. If you make this a function, it will work as long as the variable you give it is already defined. If not, you’ll still get a NameError. If you wrap the function call in try/except, it will work! I guess if you’re trying really hard to fail and you need isset() several times in your code, at least it will look nice.
def isset(variable)
try:
x = variable
del x
except NameError:
return False
return True
try:
if isset(my_var):
print "do stuff..."
except:
pass
Disclaimer: writing in one language while thinking in another is probably a bad idea…