← index #1878PR #18014
Related · high · value 0.147
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

py/gc: Remove finaliser check for AT_HEAD block type.

closedby AJMansfieldopened 2025-08-30updated 2025-09-02

This check is a remnant of the original finaliser implementation from 4f7e9f5c445b5c0b262d9dfb8fceda4830f4844b, all the way from pre-1.0. This was a valid optimisation back then, but after its ordering with other finaliser code changed in 8a2ff2ca7366f605dd55c93f6b393552b365cd10 the invariant it exploits is no longer valid, and it breaks down completely in the case of variable-length allocations made with mp_obj_malloc_var_with_finaliser.

This resulted in what I believe to be a latent bug in the VFS system, where depending on the precise memory layout, VFS finaliser routines could sometimes be inadvertently missed. This bug was discovered when encountering an identical issue with an attempt to implement __del__ for user classes in #18005.

As can be seen from the test runs with the instrumentation in #18013, this branch is also not actually hit in most normal code --- it's not actually an optimisation now; removing this condition ought to be a strict improvement to garbage collector code size and 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