[Patches] [ python-Patches-812369 ] module shutdown procedure based on GC

SourceForge.net noreply at sourceforge.net
Thu Sep 25 06:49:56 EDT 2003

Patches item #812369, was opened at 2003-09-25 10:49
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 

Category: Core (C code)
Group: Python 2.4
Status: Open
Resolution: None
Priority: 5
Submitted By: Armin Rigo (arigo)
Assigned to: Nobody/Anonymous (nobody)
Summary: module shutdown procedure based on GC

Initial Comment:
This patches changes PyImport_Cleanup() in an attempt

to make the module shutdown order more predictable in

the presence of modules that import each other. Before

it explicitely clears the globals of the modules, it

relies on the GC to try to do it more cleanly.


To prevent objects with __del__ methods from keeping

whole modules alive I actually replace each module with

a weak reference to it in sys.modules. This allows me

to find modules that remain alive after a call to

PyGC_Collect(), and then go back to the old technique

of clearing their globals.

Note that weak references to dead cycles containing

objects with finalizers have a strange property in

Python: if you use the weak reference again you can

break the cycles, but the objects with finalizers still

won't be collected because they are in gc.garbage. As

this is exactly what occurs above, I clear the

gc.garbage list explicitely before the final

PyGC_Collect() call. I'm not sure exactly what this

might do; could it release older objects that were

never put in a module but that at some time were put in

gc.garbage and whose cycles were later broken? If so,

is it a good thing to release them now? (Would it make

sense to clear gc.garbage and call gc.collect again

from time to time to check if the objects are still in

a cycle?)

This patch does not change the behavior of module

objects clearing their globals dictionary as soon as

they are deallocated. This could be work investigating.

This patch puts weak references (actually proxies) in

sys.modules but only at shutdown time. Moure thoughts

could be given towards allowing weak references during

normal program execution as well. To do so we must

ensure that 'import' statements return the real module,

not the weak proxy object, which is more difficult than

it first seems in the presence of packages.

And finally -- this patch has not really been tested,

apart from the fact that it passes the test suite.


You can respond by visiting: 

More information about the Patches mailing list