pythonic way to optimize access to imported value?

Jeff Epler jepler at unpythonic.net
Mon Nov 18 07:47:54 EST 2002


On Mon, Nov 18, 2002 at 04:03:30AM +0000, Bengt Richter wrote:
> IOW, IMO there ought to be a way to do a temporary global-side-effect-free
> import and delete all traces of its having been done -- without restarting
> the interpreter or invoking a second interpreter instance.

Let us know when you've implemented it.

Some of the problems:

Modules need not be side-effect-free.  For instance, the following is a
(very harmful) legal Python module:
    from os import system
    system("rm -rf /")

Modules may refer to other modules, so you'll need to make any other
"import"s that happen during that time special.

Unloading C modules may not work on all platforms, and may never be
possible when there are references to objects in the module.

If any nontrivial object from the module is kept, the module will be around
anyway, even if it's not listed in sys.modules.  Functions hold a reference
to the module's globals, for instance.  Any non-trivial class has methods,
and any interesting object is an instance.

I think that the presence of modules in sys.modules is used by the system
to break cycles like that of functions.  At cleanup, a module's dictionary
is cleared which breaks the module->function->module cycles and allows
collection.

It's still not exactly clear to me what all these complications would gain
me anyway...

Jeff




More information about the Python-list mailing list