Does a Function Like isset() Exist in Python?

The answer is no.

One way to see if a variable exists in the namespace is by catching exceptions when trying to access the variable. Here is an example:


try:
    if foo:
        # variable is set, do something
        pass
except NameError:
    # variable not set, do something
    pass

Avoid code like this were ever possible. This is not a recommended best practice. If you need variables that you don’t know the name of, trying using a dictionary (hash table) instead. They are made for that exact purpose.

Example of Best Practices


>>> unknown_vars = {}
>>> unknown_vars['foo'] = 2323
>>> 'foo' in unknown_vars
True
>>> 'bar' in unknown_vars
False

OR checking against globals (Thanks to bsdemon for this tip)


>>> foo = 2323
>>> 'foo' in globals()
True
>>> 'bar' in globals()
False

OR checking against locals (Thanks to bsdemon for this tip)


>>> def test():
...     a = 12
...     if 'a' in locals():
...             return 'OK'
...     else:
...             return 'SORRY'
...
>>> test()
'OK'

UPDATED: My first gut reaction was to quick make a function to handle checking against globals, but as bsdemon pointed out in his second comment, you won’t be able to use the function to check local variables. Thank you again for catching that mistake.

8 Responses to “Does a Function Like isset() Exist in Python?”

  • How about:
    >>> ’some_var’ in globasl()
    ?

  • Really good call, that would work as well, updating the article…thanks for the tip :)

  • Oh.. not so easy, consider the following example:
    def somefunc():
    a = 12
    if isset(a): # it is your ‘isset’
    return ‘OK’
    else:
    return ‘SORRY’

    >>> somefunc()
    ‘SORRY’

    This is becuase ‘a’ not in global __dict__, but in local.
    so inside function do this way:

    def rightfunc():
    a = 12
    if ‘a’ in locals():
    return ‘OK’
    else:
    return ‘SORRY’

    This one:
    >>> rightfunc()
    ‘OK’

  • Funny that you posted this…I was on my way home tonight and from work realized I made this mistake…thanks for the detailed examples :), fixing my post

  • Why would you want to emulate something like isset() in Python?

  • Good point and I don’t believe python developers should…especially since using the isset() function in PHP code is generally seen as a bad practice anyway. This post was more or less directed at first time Python developers who have a PHP background and are looking to have this question answered. Thanks for the comment!

  • Why can’t you just do something like?

    if ‘a’ in locals() or ‘a’ in globals(): print “OK”

    Not that I’ve used that a bunch - much more common, when inside a class, is something like this:

    if hasattr(self, “a”): print “OK”

    hasattr is a built-in function that basically does exactly what your top function does.

    >>> pydoc.doc(hasattr)
    hasattr(…)
    hasattr(object, name) -> bool

    Return whether the object has an attribute with the given name.
    (This is done by calling getattr(object, name) and catching exceptions.)

  • @April: yeah this would work

    if ‘a’ in locals() or ‘a’ in globals(): print “OK”

    As long as you don’t make it into a function like the example below. The above example only works if it is used directly in the function that requires it, because of local and global scope.

    def isset(var):
    if var in locals() or var in globals():
    return True
    else:
    return False

    Thanks for pointing out the hasattr(object, name) function, really is useful, especially if you plan to do reflection.

Trackbacks

  •