Can “soft references” exist in Python?

与世无争的帅哥 提交于 2019-12-03 12:31:45

Python doesn't natively offer any flavors of references besides hard (aka strong) & weak.

That said, here is a softref implementation I whipped up a year or so ago which I've been using in a few places I needed one. What it provides aren't quite actual soft references, but it comes close for most use cases. It's a little rough around the edges, but is fully functional... though it relies on some reference counting internally that means it'll probably break on anything except CPython.

In particular, I wrote it precisely for a cache of expensive-to-create long-lived objects... the SoftValueDictionary should be exactly what you're looking for.

Another option is to use a cache that maintains a certain number of objects (e.g. 100) rather than explicitly calculating their memory consumption. When an object is accessed, it is put to the top of the cache if it exists, or the object on the bottom of the cache is replaced with the new object.

Untested, but it should work in theory.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!