Search code examples
pythondynamicpython-decorators

Dynamic parameters with Python's retry decorator


I'm currently using the python retrying package which contains the @retry decorator that has a number of optional parameters. I have these parameters set correctly for our production environment with long enough wait times in between retries (below it's set to 2000 milliseconds) but I would like to set these values differently for unit testing purposes so that execution is very quick.

For example here the wait_fixed time is set to 2000 milliseconds for production but for my unit test that calls some_function() I'd like to override the wait_fixed parameter to be 1 millisecond so it executes very quickly.

@retry(stop_max_attempt_number=3, wait_fixed=2000)
def some_function(self):
    return True

The problem I'm running into is that the decorator is interpreted when the function is defined so as of yet I have not found a way to override the wait_fixed parameter from my unit tests.


Solution

  • main.py

    import settings
    from retrying import retry
    
    
    @retry(stop_max_attempt_number=settings.STOP_MAX_ATTEMPT_NUMBER, 
           wait_fixed=settings.WAIT_FIXED)
    def some_function(self):
        return True
    

    settings.py

    import json
    
    
    with open('config.json') as jsonf:
        config = json.loads(jsonf.read())
    
    WAIT_FIXED=int(config['WAIT_FIXED'])
    STOP_MAX_ATTEMPT_NUMBER=int(config['STOP_MAX_ATTEMPT_NUMBER'])
    

    config.json

    {
        "STOP_MAX_ATTEMPT_NUMBER" : "3",
        "WAIT_FIXED" : "2000"
    }
    

    Have your test runner put a suitable config.json in place.