Circular references not being cleaned up by Py_Finalize()

Paul McGuire ptmcg at austin.rr.com
Tue Mar 25 21:22:06 CET 2008


On Mar 25, 2:32 pm, blackpawn <pharmapsycho... at gmail.com> wrote:
> I've been trying to get garbage collection of circular references to
> work properly with no success then I noticed the documentation stating
> that it just doesn't:
>
> From documentation on Py_Finalize() -> "Memory tied up in circular
> references between objects is not freed. "
>
> I copy pasted the Noddy example for circular reference breaking from
> the documentation and set a break point in its Noddy_dealloc function
> and sure enough even that simple example doesn't work properly.
>
> So what's the deal here?  :)  I want all objects to be freed when I
> shut down and their destruction functions to be properly called.  Is
> there really no way to make this happen?
>
> Many thanks for any insights,
> Jim

It sounds like you are using finalizers like destructors in C++.
Don't do this.  Garbage collection is not deterministic, and is not
supposed to be.

Instead, use language features that do similar scope-driven code
execution:
- try/except/finally
- with

Put your cleanup code in the finally block, or in the context managers
__exit__ method.  These will run when the program exits the given
scope, without having to play GC shenanigans.

-- Paul



More information about the Python-list mailing list