How to use a Python weakref cache mapping keys to values, when values hold a reference to the keys? -
i have lookup cache in python mapping keys values. keys , values functions. want cache hold weak references, if functions garbage collected, disappear in cache. in case, value functions hold reference key functions:
import weakref cache = weakref.weakkeydictionary() def f(h,really_store=false): g = cache.get(h) if g none: def g(x): return h(x)*2 cache[h]=g if really_store else lambda x: "fake" return g(1) def doit(really_store): cache.clear() def h1(x): return 3 def h2(x): return 'hi!' print f(h1, really_store) print f(h2, really_store) print f(h1, really_store) print cache.keys() del h1 print cache.keys() doit(false) doit(true) this prints:
6 hi!hi! fake [<function h1 @ 0x000000000976e198>, <function h2 @ 0x000000000976ef98>] [<function h2 @ 0x000000000976ef98>] 6 hi!hi! 6 [<function h1 @ 0x000000000976ef98>, <function h2 @ 0x000000000976ef28>] [<function h1 @ 0x000000000976ef98>, <function h2 @ 0x000000000976ef28>] the weak cache behavior works if values don't hold references keys (function h1 disappears cache in first case). if values hold reference keys, weak cache doesn't release reference keys.
is there way fix this?
Comments
Post a Comment