hasattr

Checking for member existence in Python

对着背影说爱祢 提交于 2019-11-26 14:19:34
问题 I regularly want to check if an object has a member or not. An example is the creation of a singleton in a function. For that purpose, you can use hasattr like this: class Foo(object): @classmethod def singleton(self): if not hasattr(self, 'instance'): self.instance = Foo() return self.instance But you can also do this: class Foo(object): @classmethod def singleton(self): try: return self.instance except AttributeError: self.instance = Foo() return self.instance Is one method better of the

hasattr() vs try-except block to deal with non-existent attributes

非 Y 不嫁゛ 提交于 2019-11-26 12:04:39
问题 if hasattr(obj, \'attribute\'): # do somthing vs try: # access obj.attribute except AttributeError, e: # deal with AttributeError Which should be preferred and why? 回答1: hasattr internally and rapidly performs the same task as the try/except block: it's a very specific, optimized, one-task tool and thus should be preferred, when applicable, to the very general-purpose alternative. 回答2: Any benches that illustrate difference in performance? timeit it's your friend $ python -mtimeit -s 'class C