Trivial performance questions
Peter Otten
__peter__ at web.de
Fri Oct 17 10:49:59 EDT 2003
Brian Patterson wrote:
> I have noticed in the book of words that hasattr works by calling getattr
> and raising an exception if no such attribute exists. If I need the value
> in any case, am I better off using getattr within a try statement myself,
> or is there some clever implementation enhancement which makes this a bad
> idea?
In rare cases, i. e. when attribute access has side effects, there are not
only differences in performance, but also in the result:
class AskMeOnce(object):
def __getattribute__(self, name):
result = object.__getattribute__(self, name)
delattr(self, name)
return result
t = AskMeOnce()
t.color = "into the blue"
#raises an exception
#if hasattr(t, "color"):
# print t.color
#works
try:
print t.color
except AttributeError:
pass
:-)
Peter
More information about the Python-list
mailing list