[Python-ideas] Module local namespaces

Matt Draisey matt at draisey.ca
Thu Jan 4 01:20:43 CET 2007

A while ago, I developed a small PyGtk programme that could dynamically
reload all the working callbacks and logic while the GUI was still
running.  I could get away with this because of the flexible way Python
loads modules at runtime, but it ended up being a waste of time as
implementing it took more time that actually using it.  For sanity's
sake it quickly becomes clear you almost never want to rely on being
able to refer to a half initialized module.  And wouldn't it be nice if
Python enforced this.

My suggestion is that module importing occur in a temporary local
namespace that exists only until the end of the module code is executed,
then a small function could copy everything from the temporary namespace
into the module object.  The usual closure semantics would guarantee
that top-level functions could still call each other, but they would
effectively become immutable after the namespace wraps up.  The 'global'
keyword could be used at the top level in a module to force it to be
defined in the module immediately, and to ensure internal references to
the object go through the module object.

This would be a big change in module import semantics, but should have
remarkably few consequences, as it really is an enforcement mechanism
for good style.  The copying from the temporary namespace into the
module object would be a good place to insert a hook function to filter
what objects are actually published to the module.  You could by default
not copy any object indentified by a leading underscore.

More information about the Python-ideas mailing list