load a class dynamically

Jeremy Lowery jslowery at hotmail.com
Fri Nov 30 23:16:47 EST 2001


Thanks for the post,

Yes, I finally figured that out after I made the post. (Always happens that
way).

Now I'm in search of finding a way to make a dynamic modules, packages to
add the classes to. I'm writing an app that stores all of this stuff in a
ZODB and lets users write code on a server over a network. And I'm trying to
figure out a way to dynamically "pack" all of the class definitions into
modules and packages so that I can plug the base package into the namespace
before the code is run.

like one user importing Users.JLowery.ACoolModule
in the code that is going to be piped over the network, and then the
module/package structure is dynamically created from the objects in the
ZODB. (Like the User package gets put in the global namespace) (Of course,
not dynamically recreate it on every request but you get the idea.)

Jeremy





"Hans Nowak" <wurmy at earthlink.net> wrote in message
news:3C08497D.2C92F2B9 at earthlink.net...
> Jeremy Lowery wrote:
> >
> > I know that implementing this may be a little bit of work, but could
someone
> > point me in the right direction?
> >
> > Have a text file that only contains a class definition, or just a string
for
> > the sake of simplicity.
> >
> > str = "class myClass:\n\tdef __init__(self):\n\t\tself.v = 1"
> >
> > #the magical code goes here.
> >
> > obj = myClass()
> > # of course, it doesn't have to be called like that, but to
> > #get the ability to instantainate that class.
>
> You can use the exec statement, but you should end the string in
> a newline, though...
>
> >>> str = "class myClass:\n\tdef __init__(self):\n\t\tself.v = 1"
> >>> exec str
> Traceback (most recent call last):
>   File "<pyshell#2>", line 1, in ?
>     exec str
>   File "<string>", line 3
>     self.v = 1
>              ^
> SyntaxError: invalid syntax
> >>> str = str + "\n"
> >>> exec str
> >>> obj = myClass()
> >>> obj
> <__main__.myClass instance at 00AB5ED4>
> >>>
>
> --Hans






More information about the Python-list mailing list