load a class dynamically

Hans Nowak wurmy at earthlink.net
Fri Nov 30 22:07:45 EST 2001


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