deleting global namespaces

Gordon McMillan gmcm at hypernet.com
Sat Feb 5 12:53:14 EST 2000


Martin has a strange question:

(At first read, I did not understand your question; and it looks 
like that's a common problem.)

> I'm embedding Python in a multimedia engine
> 
> My idea is that each component will sit in
> a module and there will be some functions which
> will take care of starting the module and performing
> clean up upon exit.
> 
> But the problem is there is no way to force Python to
> delete module together with all variables/functions
> which exist in its global namespace - that is
> I cannot perform any clean up. Upon exit I would
> have to go through all global objects and delete
> them explicitly, but I cannot do this, because
> throughout the application one module can be
> started multiple times and each time it has to
> run like it was started for the first time.

One problem is figuring out what the expected lifetime is. How 
do you know whether two usages should share the same 
module object, or each needs it's own copy? How do you 
know when a particular one should go away?
 
> Is there some workaround (including patches to the
> source code) to do this with modules or some other
> way to create and delete new global namespace?

Sure. You can force reloads of modules; particularly from C, 
you can do nasty things to a module's __dict__.
 
> I do not want to create new subinterpreter for each
> application's component because I want all components
> to use the same built in modules and I want to pass
> an application-wide dictionary between each component's
> namespace.

Builtins are not a problem. There's only one copy.

I have no idea what you mean by "component" in this context, 
but you could create new (empty) modules (look at how 
__main__ is created) and then import the others into that 
namespace. You could add a builtin to provide access to your 
app object.

You can do about the same from pure Python by using 
__import__, exec and execfile, and managing the dicts that 
get used as globals and locals.

I think it would be saner to use explicit objects that hold the 
state you're now using the modules' globals for. You can pass 
these around, create them and destroy them, all without 
resorting to cryptic Python or reams of mind numbing C code.

- Gordon




More information about the Python-list mailing list