Generating modul classes with eval

Steve Holden steve at holdenweb.com
Wed Feb 2 16:06:55 EST 2005


Axel Straschil wrote:

> Hello!
> 
> I was fooling around with creating classes for a module with eval,
> something like:
> 
> MyModule.py:
> 
> class Base:
> 	init(self, name):
> 		self._name = name
> 
> for myclass in ['A', 'B', 'C']:
> 	code="class %s(Base):\n\tinit(self, name='%s')\n\t\tsuper(%s,
> 	self).__init(name=name)\n"%dict(myclass, myclass.lower(), myclass())
> 	... codeop and eval stuff ...
> a=A()
> print a
> 
> that gives: <class '__main__.A'>, but I want MyModule.A ;-)
> 
> Can someone give me a hint how to create classes in a module with eval
> and codeop so that they exist like the code was written in?
> 
> Thanks, 
> AXEL.
> 
You could try just importing the module - then, when it runs, its name 
won't be "__main__" but "MyModule".

regards
  Steve
-- 
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005          http://www.python.org/pycon/2005/
Steve Holden                           http://www.holdenweb.com/



More information about the Python-list mailing list