Question about __getattribute__/__getattr__

Joao Prado Maia jpm at papercut.org
Mon Sep 30 17:51:16 EDT 2002


On Mon, 30 Sep 2002, holger krekel wrote:

> The important lines from the above link are:
> 
> def __call__(self, *args):
>         if not self.memo.has_key(args):
>             self.memo[args] = self.fn(*args)
>         return self.memo[args]
> 
> and 'args' is a tuple of arguments.  
> 'args[0]' would give you the first argument, for example.  
> 

Correct. However, the same is not valid for __getattr__. The first and 
only parameter of this magic method is the attribute/method name that you 
are trying to access. It doesn't give you the list of arguments passed to 
a method.

So on my example:

"""
class Real_Class:
    def real_method(self, name):
        print name

class Cache:
    r = None

    def __init__(self):
        self.r = Real_Class()

    def __getattr__(self, attr):
        cached_value = self.get_cache(attr)
        if cached_value == None:
            return getattr(self.r, attr)
        else:
            return cached_value

    def get_cache(self, attr):
        return None

if __name__ == '__main__':
    t = Cache()
    t.real_method('spam')
"""

'attr' is the actual method name I was trying to call, using the 
't.real_method('spam')' line in there.

My question is, how do I get the actual argument list from inside 
__getattr__, so I can create an unique method/argument list signature for 
the cached files ? :)

I'm guessing there must be some deep magic to do this, but I couldn't find 
this anywhere.

Cheers,
Joao





More information about the Python-list mailing list