1

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?

bbd108
  • 958
  • 2
  • 10
  • 26

1 Answers1

1

In your renew decorator you are not passing instance parameter when calling the decorated function from wrapper. Wherever you want to call your func from wrapper, call it like this:

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.

user47
  • 1,080
  • 11
  • 28
  • 1
    thanks, just posting here (may want to update your answer if it is unclear to others) in each return, must be `return func(self, *args, **kwargs)` – bbd108 Aug 25 '22 at 17:44