Skip to content

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

Description

@bastitva0-blip

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error
    No fields configured for issues without a type.

    Projects

    Status
    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions