dynamically generating a module
Delaney, Timothy
tdelaney at avaya.com
Tue Nov 13 19:02:27 EST 2001
> From: Steven D. Majewski [mailto:sdm7g at Virginia.EDU]
>
> On 13 Nov 2001, Hung Jung Lu wrote:
>
> > Here is one more challenge: is it possible to create a module on the
> > fly?
> >
> > Suppose I have the ASCII Python source code of a
> module-to-be, or even
> > better, suppose that I have the compiled byte code of a
> module-to-be,
> > stored in a Python string. Is there a simple way (meaning
> not tweaking
> > at C++ level) of making the module-to-be into a real module, without
> > hitting the harddrive?
>
> Sure: all you have to do is create an empty module and exec the code
> in that modules namespace:
Another useful possibility is to stick a class instance into sys.modules.
class NewModule:
a = 1
b = 2
def func (self, a):
""""""
return a
import sys
sys.modules['newmodule'] = NewModule()
import newmodule
print newmodule.a
print newmodule.b
print newmodule.func(5)
Tim Delaney
More information about the Python-list
mailing list