Search code examples
pythondjangodjango-testsdjango-cache

Wrap python decorator with another decorator


I have a common decorator call throughout my Django codebase:

@override_settings(
    CACHES={
        **settings.CACHES,
        "default": generate_cache("default", dummy=False),
        "throttling": generate_cache("throttling", dummy=False),
    }
)
def test_something():
    ...

The decorator code is too verbose. I'd love to wrap this code into a new decorator called @use_real_cache so the test function looks much cleaner:

@use_real_cache
def test_something():
    ...

How can I wrap a decorator with another decorator?


Solution

  • Just assign it to a value:

    use_real_cache = override_settings(
        CACHES={
            **settings.CACHES,
            'default': generate_cache('default', dummy=False),
            'throttling': generate_cache('throttling', dummy=False),
        }
    )
    
    # …
    
    @use_real_cache
    def test_something():
        # …
        pass

    This is essentially what happens in the first code sample of the question, except that you do not assign it to an (explicit) variable.