Add `cache_info` and `cache_clear` to `functools.WRAPPER_ASSIGNMENTS`

If you currently wrap (using functools.wraps) some function which is already wrapped with functools.lru_cache you’ll lose the methods cache_info and cache_clear.
You can of course manually assign these, or pass them as extra values to the assigned argument of wraps.
However it seems natural if wraps and lru_cache play nice together by default since they are from the same module functools.

Consider the following code:

from functools import wraps
from functools import lru_cache

def wrap(func):
    def new_func(x):
        return func(x)
    return new_func

def func(x):
    return x + 1

print(func.cache_parameters())  # {'maxsize': 128, 'typed': False}
print(func.cache_info())  # raises AttributeError: 'function' object has no attribute 'cache_info'

With the suggested code in the branch below the above code prints the cache info without any additinal arguments to wraps.

For other functions which are not wrapped in lru_cache the attributes are simply not assigned.

See Comparing python:main...AckslD:wraps-lru-cache · python/cpython · GitHub for implementation.

1 Like