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
Bug report
Bug description:
Lib/ipaddress.pyuses@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_cacheon instance methods causes a memory leak: the global cache holdsa reference to
self, preventing garbage collection even after all other referencesto the instance are dropped.
This can be demonstrated with:
The same file already uses
@functools.cached_propertyfor other properties(e.g.
with_prefixlen,compressed), which correctly ties cache lifetime tothe instance. Those do not leak:
Fix: Replace
@functools.lru_cache()with@functools.cached_propertyonthe 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