Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

python - Passing parameters to decorator at runtime

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 returns True.
    """
    def deco_retry(f):
        def f_retry(*args, **kwargs):
            mtries  = tries
            rv = f(*args, **kwargs)
            while mtries > 0:
                if rv is True:
                    return True
                mtries -= 1
                time.sleep(delay)
                rv = f(*args, **kwargs)
            return False
        return f_retry
    return deco_retry

I can use it like this

    @retry_until_true(20, delay=30)
    def check_something_function(x, y):
        ...
        return True

But is there a way to pass different values for 'tries' and 'delay' to the decorator at runtime, so that 20 and 30 are variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...