isset() php function equivalent in python

simple-diagram-tree-125x125

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.

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…

Posted by admica   @   20 June 2011

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

Previous Post
« Thread control in python - how to safely stop a thread
Next Post
Compile python scripts without running them »
Powered by Wordpress   |   Lunated designed by ZenVerse