python / python/cpython

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

Đang mở
#152,753 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

stdlib type-bug
Ngôn ngữ chính
Python
Star
77.2k
Fork
35.9k
Chỉ số merge pull request
Chỉ số pull request đang chờ

Mô tả

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

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Đọc bốn thuộc tính bị ảnh hưởng trong Lib/ipaddress.py và so sánh chúng với các cách sử dụng cached_property hiện có trong tệp đó. Xác nhận thay đổi dựa trên các ví dụ về weakref và thu gom rác để bốn thực thể địa chỉ và mạng có thể được thu gom sau khi các tham chiếu đến chúng bị loại bỏ.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
backend
Loại issue
Lỗi
Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
35/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.