Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call decorator with class variable in python

Probably I am approaching the problem in the wrong way and there is a simpler solution, but here is my problem.

I have a decorator defined like this:

def my_decorator(argument):
    def wrap(f):
       def wrapped_f(*args, **kwargs):
           .... # does something with argument
       return wrapped_f
    return wrap

then I defined a class that looks like this:

class MyClass(object):
    def __init__(argument):
        self.argument = argument

    @my_decorator(self.argument)  # !this is an error! 
    def my_method(self):
       .... # does something

Clearly what I wrote is wrong because at the decorator level I cannot access self, but what's the right approach to solve this problem?

like image 595
Giovanni Di Milia Avatar asked Feb 12 '23 16:02

Giovanni Di Milia


1 Answers

You could have the decorator access self.argument inside wrapped_f:

def mydecorator(f):
   def wrapped_f(self, *args, **kwargs):
       argument = self.argument
       .... # does something with argument
       return f(self, *args, **kwargs)
   return wrapped_f
return wrap

If the variable being passed as argument changes depending on the function being decorated, you can pass it to the decorator as a string and use getattr to get it from self:

def my_decorator(arg_name):
    def wrap(f):
       def wrapped_f(self, *args, **kwargs):
           argument = getattr(self, arg_name)
           .... # does something with argument
       return wrapped_f
    return wrap

class MyClass(object):
    def __init__(self, argument):
        self.argument = argument

    @my_decorator("argument")
    def my_method(self):
       .... does something
like image 155
dano Avatar answered Feb 15 '23 05:02

dano