Skip to content

gh-152753: Fix memory leak in ipaddress properties by switching to cached_property#152790

Open
bastitva0-blip wants to merge 5 commits into
python:mainfrom
bastitva0-blip:fix/ipaddress-lru-cache-memleak
Open

gh-152753: Fix memory leak in ipaddress properties by switching to cached_property#152790
bastitva0-blip wants to merge 5 commits into
python:mainfrom
bastitva0-blip:fix/ipaddress-lru-cache-memleak

Conversation

@bastitva0-blip

@bastitva0-blip bastitva0-blip commented Jul 1, 2026

Copy link
Copy Markdown

Fixes #152753

Description

Using @functools.lru_cache() on instance methods creates a global cache that retains references to self. This keeps the instances alive indefinitely and prevents proper garbage collection, creating a memory leak.

This PR resolves the issue by replacing the lru_cache decorators with @functools.cached_property on the affected lookup properties within Lib/ipaddress.py. This correctly ties the cache lifetime to the lifecycle of the instance itself.

Changes

  • Replaced the decorators on four instance properties: IPv4Address.is_private, IPv4Address.is_global, IPv4Network.is_global, and IPv6Address.is_private.
  • Added '__dict__' to __slots__ inside IPv4Address so that cached_property has an active instance dictionary to store its cached values.
  • Added '__dict__' to __slots__ inside IPv6Address for the same reason, ensuring we preserve the memory efficiency benefits of slots for the remaining fixed attributes.

@python-cla-bot

python-cla-bot Bot commented Jul 1, 2026

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app

bedevere-app Bot commented Jul 1, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@bastitva0-blip bastitva0-blip force-pushed the fix/ipaddress-lru-cache-memleak branch from f95478c to a1fd3d8 Compare July 1, 2026 14:49
@bedevere-app

bedevere-app Bot commented Jul 1, 2026

Copy link
Copy Markdown

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

@bastitva0-blip

Copy link
Copy Markdown
Author

All 49 checks have successfully passed! The PR is fully updated with the base branch and ready for review whenever a maintainer has some time. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant