Passing parameters to decorator at runtime

前端 未结 2 2054
闹比i
闹比i 2021-01-12 08:08

If I create a python decorator function like this

def retry_until_true(tries, delay=60):
    \"\"\"
    Decorator to rety a function or method until it retur         


        
相关标签:
2条回答
  • 2021-01-12 08:10

    You can use a class as a decorator, with instance variables for tries and delay:

    class RetryUntilTrue(object):
        def __init__(self, f=None, tries=10, delay=30):
            self.f = f
            self.tries = tries
            self.delay = delay
    
        def __call__(self, *args, **kwargs):
            if self.f is None:
                self.f = args[0]
            else:
                tries = self.tries
                while tries:
                    if self.f(*args, **kwargs):
                        return True
    
                    tries -= 1
                    time.sleep(self.delay)
    

    Usage:

    @RetryUntilTrue
    def foo(x):
        pass
    
    foo.tries = 20
    foo.delay = 1
    
    @RetryUntilTrue(tries=100, delay=9999)
    def bar(x):
        pass
    
    bar.tries -= 1
    bar.delay = foo.delay
    
    0 讨论(0)
  • 2021-01-12 08:34

    Sure you can, just nest your function definition in another function, for example:

    def explicit_setup_func(tries, delay=60):
        @retry_until_true(tries, delay)
        def check_something_function(x, y):
            # Code
    

    However, the class decorator solution is more practical.

    0 讨论(0)
提交回复
热议问题