How best to check for existance of an attribute?

Greg Krohn infinitystwin.SPAM at IS.BAD.yahoo.com
Tue Dec 25 16:49:30 EST 2001


"Roy Smith" <roy at panix.com> wrote in message
news:roy-DD8C6B.16193025122001 at news1.panix.com...
> I've got a function which augments an object passed to it by adding a new
> attribute.  Something like this:
>
> def addStuff (obj):
>    obj.newAttr = "stuff"
>
> I want it to be an error to call addStuff() more than once for a given
> object.  The simpliest way to do this would be with something like perl's
> defined() function:
>
> def addStuff (obj):
>    if defined (obj.newAttr):
>       raise MultipleCallError
>    else:
>       obj.newAttr = "stuff"
>
> What's the best way to simulate defined()?  I could think of a few
> possibilities.  For example, either of the following seem like they would
> work:
>
> def addStuff (obj):
>    if 'newAttr' in dir (obj):
>       raise MultipleCallError
>    else:
>       obj.newAttr = "stuff"
>
> def addStuff (obj):
>    try:
>       obj.newAttr
>       raise MultipleCallError
>    except AttributeError:
>       obj.newAttr = "stuff"
>
> Any reason to pick one over the other, or perhaps a third way?

This is what I would do:

def addStuff (obj):
    if hasattr(obj, 'stuff'):
        raise MultipleCallError
    else:
        setattr(obj, 'stuff', None)

But then again, that's just me.

greg





More information about the Python-list mailing list