tenacity icon indicating copy to clipboard operation
tenacity copied to clipboard

How to set default @retry parameters

Open chrigrahcisco opened this issue 8 years ago • 3 comments

Is there as way to set the default @retry parameters while still allowing the clean-and-easy use of the @retry decorator?

For example, I have a module that provides database methods. I really just want to use @retry with the same exact parameters for all instances. I'd love to define those once and have them simply apply @retry to all the individual methods vs having to specify the parameters with each @retry lines like this.

@retry(stop=stop_after_attempt(5), wait=wait_fixed(1), reraise=True, before_sleep=before_sleep_log(logger, logging.DEBUG))
def my_function()

Or is the only option to set a retryer? Then call my functions with .call() like:

r = tenacity.Retrying(
            wait=tenacity.wait_fixed(1),
            stop=tenacity.stop_after_attempt(5),
            reraise=True,
            before_sleep=before_sleep_log(logger, logging.DEBUG,
        )
r.call(my_function)

chrigrahcisco avatar Oct 25 '18 17:10 chrigrahcisco

You can use parameter expansion with your options as a dictionary.

DB_RETRY = {"stop":stop_after_attempt(5), "wait": wait_fixed(1), "reraise": True, 
"before_sleep": before_sleep_log(logger, logging.DEBUG))}

@retry(**DB_RETRY)
def my_function():
    pass

@retry(**DB_RETRY)
def anotha_func():
    pass

Brian-Williams avatar Oct 25 '18 21:10 Brian-Williams

Or just cache it

db_retry = retry({"stop":stop_after_attempt(5), "wait": wait_fixed(1), "reraise": True, 
"before_sleep": before_sleep_log(logger, logging.DEBUG))})

@db_retry
def some_func():
    pass

When you call @somedeco(param=val), the order of operations will evaluate somedeco(param=val) first, and then the @ operator will apply the "wrap" as normal

Also, if you use Brian's example, ensure you use the splat operator **{'param_name': 'value', ...}

hughesjj avatar Oct 26 '18 01:10 hughesjj

Many thanks. Opted for param expansion.

chrigrahcisco avatar Oct 29 '18 21:10 chrigrahcisco