Build classes/packages dinamicaly

vincent wehren vincent at visualtrans.de
Tue Dec 16 19:29:01 CET 2003


"Paulo Pinto" <paulo.pinto at cern.ch> schrieb im Newsbeitrag
news:brmpt2$7nn$1 at sunnews.cern.ch...
| 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?

Sure

Put this in a file called "dynmods.py" or something:

from types import ModuleType
def generate_module(dynmod):

    exec '%(dynmod)s = ModuleType("%(dynmod)s")' % vars() in globals()
    dynmod = globals()[dynmod]
    exec "def something():\n\tprint 'hello from', __name__\n" in
dynmod.__dict__
    return dynmod

fire up a shell and:

>>> import dynmods
>>> dummy = dynmods.generate_module("dummy")
>>> print dummy
<module 'dummy' (built-in)>
>>> dummy.something()
hello from dummy
>>>

Is this what you were looking for?

Regards

Vincent Wehren


|
| 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