15.10.20 20:49, Ram Rachum пише:
> Hi everyone,
> 
> For many years, I've used a `cache` decorator that I built
> <https://github.com/cool-RR/python_toolbox/blob/master/python_toolbox/caching/decorators.py#L36>
> for caching Python functions. Then `functools.lru_cache` was
> implemented, which is much more standard. However, as far as I know, it
> holds normal references to its keys, rather than weak references. This
> means that it can cause memory leaks when it's storing items that don't
> have any references elsewhere. This often makes me reluctant to use it. 
> 
> What do you think about supporting weakrefs in for keys lru_cache?
> 
> If I remember correctly, the main difficulty was that not all keys are
> of a type that can be weakreffed. If I remember correctly again, I've
> solved this by including logic that attempts a weakref when possible,
> and degrades to a strong ref. What do you think about that? 

Not all objects support weak references. The function can have arguments
that support weak references and those which do not. Instead of spending
time on trying to create a weak reference to objects which do not
support it, it is better to create a weak reference only for arguments
which expected to support it.

Currently you can implement it by adding yet one function which wraps
arguments in weak references, and unwrap them in the cached function.

def func(a, b, c):
    return _cached_weakref_func(a, weakref.ref(), c)

@lru_cach()
def _cached_weakref_func(a, bref, c):
    b = bref()
    ... # implementation

You can control for which arguments you create a weak reference.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BN7MKYHUFOA3ZCBI2H2TWL6HXCTQC4QQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to