How to set default @retry parameters
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)
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
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', ...}
Many thanks. Opted for param expansion.