isset() php function equivalent in python

If you need this, you’re probably doing it wrong. But if you really must check to see if a variable has been assigned yet, there’s nothing really stopping you. Here’s one way of implementing it.
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.
|
1 2 3 4 5 6 |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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…