Build classes/packages dinamicaly

Naerbnic naerbnic at
Tue Dec 16 23:07:37 CET 2003

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

Well, this isn't the perfect solution, but you can create modules in
the system at runtime like so:

In your code:
>>> mymodule = generate_module() #As above
>>> import sys
>>> sys.modules['dummy'] = mymodule

Now, the user can just do the following:
>>> import dummy
>>> dummy.something()

It's not _quite_ what you want, since it doesn't automatically include
it, but it's pretty easy to do. Furthermore, if you standardize the
name of the module, you can just have the user import that by default,
and then use whatever dynamic content you've put inside.

Also, note that mymodule can actually be anything, although you should
still use a value that responds to __getattr__ (anything else would be
really confusing, and probably a Bad Thing).

I hope this helps.

- Brian Chin

More information about the Python-list mailing list