← index #1878PR #18840
Related · high · value 0.324
QUERY · ISSUE

py: __del__ special method not implemented for user-defined classes

openby israelg99opened 2016-03-07updated 2024-12-05
py-core

Example:

import gc

class Foo():
    def __del__(self):
        print('__del__')

f = Foo()
del f

gc.collect()

According to this post #1802, gc.collect() should collect the object after the del and call the finaliser, but the finaliser is never called, any ideas?

I know that a good programming practice is to assume that __del__ may never be called, but hey, this still should work :)

CANDIDATE · PULL REQUEST

Implement `weakref` module from `__del__` only.

openby AJMansfieldopened 2026-02-18updated 2026-03-02
py-core

Summary

This PR demonstrates an alternate concept to #18822 for a, implementation of the weakref module that relies more heavily on python-language code atop the __del__ method plus a much simpler c-language "weak pointer" primitive.

This is built on #18005, though in theory any implementation of __del__ that handles cyclic isolates correctly would also work.

Testing

I've pulled in all tests from #18822 for comparison. Note that few of the tests pass as written, but for many of them the distinction is down to just sequential ordering. There's also one lingering exception-handling issue but I'm confident I'll be able to resolve it.

I've flat-enabled this feature on all ports for the sake of size comparison --- this is not intended to be merged as such.

Trade-offs and Alternatives

This is an alternative proposal to #18822, aimed at a much smaller code size suitable for all ports, but likely with much worse runtime performance.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied