How best to check for existance of an attribute?
Roy Smith
roy at panix.com
Tue Dec 25 16:19:30 EST 2001
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?
More information about the Python-list
mailing list