Build classes/packages dinamicaly

Paulo Pinto paulo.pinto at cern.ch
Tue Dec 16 06:22:10 EST 2003


Thanks it is want I was looking for.
However I still have a problem.

I want to make the module available to the
caller as if he did an import.

For example, if I make the following call

some_module.generate_module('dummy')

Where some_module is the module that generates
modules dinamicaly, and dummy is the name of the
new module.

I would like to be able to do

dummy.something()

after that call.

I've discovered that if I do something like this

globals()['dummy'] = module_instance_returned_by_new.module()


It works, but it must be done at the same level I want to
call dummy.something() and not from inside some_module. Because
if I do it inside the module, globals() will be refering to the
module globals and not to parent scope.

Basically I would like to import the generated module to the
module that is invoking generate_module() like an uplevel in
Tcl.

Is this possible?

Cheers,
Paulo Pinto

Peter Otten wrote:
> Paulo Pinto wrote:
> 
> 
>>I have a package that generates classes from a
>>set of XML files using exec.
>>
>>So far the classes appear in the global namespace.
>>
>>Is there any way to also create packages dinamicaly
>>and add the classes to those packages?
>>
>>Thanks in advance,
>>Paulo Pinto
> 
> 
>>>>import types
>>>>mymodule = types.ModuleType("mymodule")
>>>>exec "def demo():\n\tprint 'hello from', __name__\n" in
> 
> mymodule.__dict__
> 
>>>>mymodule.demo()
> 
> hello from mymodule
> 
> 
> Seems to work. I haven't used it myself, though.
> 
> Peter
> 





More information about the Python-list mailing list