python / python/cpython

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

Open
#152,753 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the four affected properties in Lib/ipaddress.py and compare them with the existing cached_property uses in that file. Confirm the change against the weakref and garbage-collection examples so the four address and network instances can be collected after their references are dropped.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.