[Python-Dev] Details on Python shutting down

Martin v. Löwis martin@v.loewis.de
16 Jun 2003 09:19:12 +0200


"Brett C." <bac@OCF.Berkeley.EDU> writes:

> So, what exactly does Python do during shutdown?  

Part of what happens is pythonrun.c:Py_Finalize.

> I assume all objects get cleaned up and have their __del__ methods
> called if they have them.

No. Python never explicitly destroys object. They end life solely by
having their refcount drop to zero.

> Tim mentioned in the patch that Python "systematically sets
> module-global bindings to None".  So I assume this means that
> referencing *any* globals during shutdown just doesn't work since it
> might be None (which makes sense in the case of this bug report).

No. It depends on the order of things. There may be globals which you
can refer to; other globals may have been zapped.

> Is there any specific order to this teardown?

To shutdown in general: yes, see Py_Finalize. The order of module
teardown is defined in import.c:PyImport_Cleanup. Modules are zapped
in the order in which PyDict_Next returns them (skipping
__builtins__).

> I remember Tim saying that in __del__ methods you had to have
> locally bound anything you needed to call since otherwise it could
> be gone when you need it.

It may be that in specific cases, you can be sure that things will be
there. In general, binding stuff in __del__ parameters or in self is a
good idea.

Regards,
Martin