python / python/cpython

ipaddress: lru_cache on instance methods causes memory leak (use cached_property instead)

オープン
#152,753 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

stdlib type-bug
主要言語
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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

Lib/ipaddress.py にある影響を受ける4つのプロパティを読み、そのファイル内に既存する cached_property の使用箇所と比較してください。weakref とガベージコレクションの例に照らして変更を確認し、参照を削除した後に4つのアドレスおよびネットワークのインスタンスが回収されることを確認してください。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
backend
issue の種類
バグ
難易度
2/5
見積もり時間
1〜3時間
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。