Closed
Description
Bug report
Checklist
- I am confident this is a bug in CPython, not a bug in a third-party project
- I have searched the CPython issue tracker,
and am confident this bug has not been reported before
CPython versions tested on:
CPython main branch
Operating systems tested on:
Linux
Output from running 'python -VV' on the command line:
Python 3.13.0a0 (heads/main:d63972e289, Aug 21 2023, 22:29:24) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)]
A clear and concise description of the bug:
The following script will never delete _socket.socket
type:
import _socket
# uncomment to workaround the bug
#_socket.CAPI = None
_socket = None
import sys
del sys.modules['_socket']
import gc
gc.collect()
print("exit")
Example on a Python debug build:
$ ./python -X showrefcount script.py
exit
[408 refs, 260 blocks]
The GC cannot visit the strong reference to the type stored in _socket.CAPI
capsule (C API). In Python, creating a heap type creates a reference cycle. For example, a type MRO contains the type. Methods also contain a strong reference to their type.
$ ./python
Python 3.13.0a0 (heads/main:d63972e289, Aug 21 2023, 22:29:24) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)] on linux
>>> import _socket
>>> t=_socket.socket
>>> t.__mro__[0] is t
True
See also:
- https://pythondev.readthedocs.io/garbage_collector.html#reference-cycles
- https://vstinner.github.io/debug-python-refleak.html
- https://vstinner.github.io/subinterpreter-leaks.html