How to prevent hasattr from retrieving the attribute value itself

I have a class that implements virtual attributes using __getattr__ . Attributes can be expensive, for example. fulfilling the request. Now I use a library that checks if my object has an attribute before it gets it.

As a result, the request is executed twice instead of one. Of course, it makes sense to actually execute __getattr__ to really know if the attribute exists.

 class C(object): def __getattr__(self, name): print "I was accessed" return 'ok' c = C() hasattr(c, 'hello') 

Is there any way to prevent this?

If Python supports __hasattr__ , then I could just check if the request exists, on the contrary, it actually starts it.

I can create a cache, but it is heavy, as the request may have parameters. Of course, the server can cache the requests themselves and minimize the problem, but it is still difficult if the requests return a large amount of data.

Any ideas?

+7
python getattr
source share
2 answers

Although I initially did not like the idea of ​​cheating monkeys, being a "bad idea" in general, I came across a very neat solution since 1999.

http://code.activestate.com/lists/python-list/14972/

 def hasattr(o, a, orig_hasattr=hasattr): if orig_hasattr(o, "__hasattr__"): return o.__hasattr__(a) return orig_hasattr(o, a) __builtins__.hasattr = hasattr 

Essentially, it creates support for __hasattr__ in Python, which in my opinion would initially be an optimal solution.

+3
source share

I think this is usually a bad template, but you can always check the object underlying __dict__ .

 In [1]: class A(object): ....: @property ....: def wha(self): ....: print "was accessed" ....: In [2]: A.__dict__ Out[2]: <dictproxy {'__dict__': <attribute '__dict__' of 'A' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'A' objects>, 'wha': <property at 0x10f6b11b0>}> In [3]: a = A() In [4]: "wha" in a.__class__.__dict__ Out[4]: True 
0
source share

All Articles