Self-coded RSS A blog on Python, WebOb, programming technique and miscellaneous projects by Sergey Schetinin.
Fast weak key dictWhat follows is performance trick to make cache dictionaries as fast as possible. This addresses a specific case when you create an “addon” or proxy objects and you want at most one such proxy per object. (Another common use is attaching some metadata to the object) The way to accomplish this is to maintain the object → proxy registry and create new proxies on-demand. However, such a registry end up holding a reference to every object used. This is really bad, because it’s pretty much a memory leak that a garbage collector cannot fix. To fix that one can use
What makes it work are two things, one is that the weakrefs accept a callback that will get called when the object is destroyed. The argument to the callback is the weakref, so what the The other thing is that weak references are compared (and hashed) based on the object they reference, the callbacks are not compared. What that means is that One last thing to remember, is that if proxy holds a reference to ob, that reference should be weak, otherwise there’s a non-collectable reference cycle. You can also create a similar pattern analogous to For some additional discussion see original Google+ post. |