Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent hasattr from retrieving the attribute value itself

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?

like image 666
koriander Avatar asked May 17 '15 18:05

koriander


People also ask

Which method will ensure that an attribute has been defined before you access it Hasattr Hasattr () Hasattr _( Hasattr?

Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false.

Which method will ensure that an attribute has been defined before you access it?

getattr() – This function is used to access the attribute of object. hasattr() – This function is used to check if an attribute exist or not. setattr() – This function is used to set an attribute.

How do you check that obj1 has an attribute name?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

What is Hasattr () in Python?

Python hasattr() Function The hasattr() function returns True if the specified object has the specified attribute, otherwise False .


1 Answers

Although initially I was not fond of the idea of monkey patching, being a "bad idea" in general, I came across a very neat solution from 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 is what I thought originally would be the optimal solution.

like image 153
koriander Avatar answered Sep 29 '22 02:09

koriander