ipaddress: lru_cache on instance methods causes memory leak (use cached_property instead)
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
Lib/ipaddress.py uses @functools.lru_cache() on four instance method properties:
IPv4Address.is_private(line 1321)IPv4Address.is_global(line 1343)IPv4Network.is_private(line 1552)IPv6Address.is_private(line 2089)
Using lru_cache on instance methods causes a memory leak: the global cache holds
a reference to self, preventing garbage collection even after all other references
to the instance are dropped.
This can be demonstrated with:
import ipaddress, gc, weakref
a = ipaddress.IPv4Address('192.168.1.1')
ref = weakref.ref(a)
a.is_private # trigger the cache
del a
gc.collect()
print(ref() is not None) # True — instance is NOT collected (leak!)
The same file already uses @functools.cached_property for other properties
(e.g. with_prefixlen, compressed), which correctly ties cache lifetime to
the instance. Those do not leak:
n = ipaddress.IPv4Network('192.168.1.0/24')
ref = weakref.ref(n)
_ = n.with_prefixlen
del n
gc.collect()
print(ref() is not None) # False — correctly collected
Fix: Replace @functools.lru_cache() with @functools.cached_property on
the four affected properties.
I would like to work on a fix for this issue.
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Linked PRs
- gh-152790
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
阅读 Lib/ipaddress.py 中受影响的四个属性,并将它们与该文件中现有的 cached_property 用法进行比较。根据 weakref 和垃圾回收示例确认此更改,以确保在删除对四个地址和网络实例的引用后,它们能够被回收。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 2/5
- 预计耗时
- 1-3 小时
- 活跃度
- 停滞
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100