I have a class that implements virtual attributes using __getattr__
. The attributes can be expensive, e.g. performing a query. Now, I am using a library which checks if my object has the attribute before actually getting it.
As a consequence, a query is executed two times 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 supported __hasattr__
then I could simply check if the query exists, has opposed to actually run it.
I can create a cache, but it is heavy since a query might have parameters. Of course, the server might cache the queries itself and minimise the problem, but it is still heavy if queries return a lot of data.
Any ideas?
name
only, so that could be just a dictionary. BTW, why do you want to make it look like an attribute? – Quadrathasattr
is not a light-weight test for an attribute; it callsgetattr
essentially liketry: getattr('name'); except AttributeError: return False; else: return True
. – Lionhasattr
, which would not be recommended. If there is no way to avoid callinghasattr
, I believe your only choices are caching the result or allowing the query to run twice. – Sabir