Katsu
Katsu

Reputation: 1958

Python __getattribute__ and wrapper of method

I want to call a wrapper method of function with argument just before I call specific method. So I guess I have to ovewrite __getattribute__ method.

Here is an example of code:

def wrapper(func):
    return func * 2

class A(object):
    def test(self, arg):
        return arg + 1

    def __getattribute__(self, name):
        if name in ['test']:
            return wrapper(super(A, self).__getattribute__(name))
        return super(A, self).__getattribute__(name)

The matter is that getattribute is called when test return the value. What I want is to be able to catch test with the arguments and define the wrapper method like this:

def wrapper(func, *args, **kwargs):
    print "do some stuff"
    return func(*args, **kwargs)

Upvotes: 2

Views: 2425

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124608

Use a factory function to return your wrapper:

def decorate(f):
    def wrapper(*args, **kw):
        return f(*args, **kw) * 2
    return wrapper

Here f is closed over by wrapper(), so it can access the name when called.

Then return this in the __getattribute__ hook:

def __getattribute__(self, name):
    result = super(A, self).__getattribute__(name)
    if name in ('test',):
        return decorate(result)
    return result

Of course, you could also just apply decorate as a decorator on test then:

class A(object):
    @decorate
    def test(self, arg):
        return arg + 1

Upvotes: 4

semptic
semptic

Reputation: 654

If I understand you correctly, you can use a decorator.

def wrapper(func):
    def _wrapper(*args, **kwargs):
        return func(*args, **kwargs) * 2

    return _wrapper

class A(object):
    @wrapper
    def test(self, arg):
        return arg + 1

Upvotes: 1

Related Questions