Home > other >  Python decorator within function, needs class within method?
Python decorator within function, needs class within method?

Time:08-26

Going off of How can I define decorator method inside class? and Accessing self within decorator function within a Python class, I have the following code:

class Custom():
    def __init__(self, var):
        self.var = var

    def renew(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                print('refreshing')
                self.refresh()
                return func(*args, **kwargs)
        return wrapper

    def refresh(self):
        self.var = 'refreshed'

    @renew
    def get_something(self):

        print(self.var)
        raise Exception

test = Custom('a')
test.get_something(test)

Which returns exactly what I want (pretend that the raise Exception is a expiration timeout, where var expires after some time, am just forcing an Exception here):

a
refreshing
refreshed
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
...

However, is there any way to not require the class instance test to be in the class method, namely test.get_something(test) -> test.get_something()? Or is this best practice? What is the best way to handle something like this?

CodePudding user response:

In your renew decorator you are not passing instance parameter when calling the decorated function from wrapper. You need to pass it as

func(self, *args, **kwargs)

Once you correct the invocation call inside wrapper, you no longer need to pass class instance object when invoking your decorated function. So test.get_something() would work now.

  • Related