Is it posible to get a reference to an object instance within a function decorator in Python?

StackOverflow https://stackoverflow.com/questions/21851548

  •  13-10-2022
  •  | 
  •  

Pergunta

Given that functions are passed to decorator as an argument, would it be possible to get a reference of the object instance via the argument of the method being decorated? For example below method1 is being decorated and I want to print the name of the object instance. From my initial research it looks like I might need to use a mixin to keep track of class instances and search/filter for the right object however this seems a little heavy; given that the method has a reference to its object via self. it is posible to use that same reference to print the name of the instance with the decorator scope ?

Thanks

def customdecorator(f):
    print f.self.method2(a,b, params) // where owner would be the reference to t (self)

class Test(object):

    def __init__(self, name):
         self.name = name

    @customdecorator
    def method1(self):
        return 1

    def method2(self, a,b):
        #do something





t = Test()
Foi útil?

Solução 2

The decorator is evaluated when the class is declared. Thus, no object is present there and there is no way to get the object from inside the decorator.

Please see @user2357112’s answer on how to get the object at function call time though.

Outras dicas

import functools

def nameprinting(f):
    @functools.wraps(f)
    def wrapper(self, *args, **kwargs):
         print self.name
         return f(self, *args, **kwargs)
    return wrapper

When a decorator is called, it's supposed to apply some transformation to the function given as an argument, creating a new function. When that function is called, it has a self to work with. In this case, the returned function prints self's name, then delegates to f.

(functools.wraps is a helper that copies f's docstring and a few other things to the wrapper function.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top