How best to check for existance of an attribute?

Michael Hudson mwh at python.net
Tue Dec 25 16:32:21 EST 2001


Roy Smith <roy at panix.com> writes:

> 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()?

By using hasattr?

bash-2.00$ python -c "print hasattr.__doc__"
hasattr(object, name) -> Boolean

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

> I could think of a few possibilities.  For example, either of the
> following seem like they would work:
[...]
> def addStuff (obj):
>    try:
>       obj.newAttr
>       raise MultipleCallError
>    except AttributeError:
>       obj.newAttr = "stuff"

This is more-or-less what hasattr does, but hasattr() almost certainly
expresses your intent better.

Cheers,
M.



More information about the Python-list mailing list