Best way to create a class dynamically on the fly?

holger krekel pyth at devel.trillke.net
Sat Sep 28 16:46:45 EDT 2002


Robert Oschler wrote:
> What is the best way to create a Python class dynamically at runtime?  A
> sample or doc would be great.  I'm a veteran C++ programmer so this concept
> is very alien to me as you can imagine (dynamically created classes).  An
> example that would show the creation of a descendant (sub-class), and a
> another example showing the creation of an ancestor class would be perfect.

Chances are you don't need dynamically generated classes. python is
naturally dynamical. When i came from C++ to python i came up with
using 'exec' followed by a dynamically generated string defining the
function. 

Another way is to use the new - module, e.g.

>>> c = new.classobj('myclass', (),{})
>>> c
>>>
<class __main__.myclass at 0x82eb3b4>
>>> c()
<__main__.myclass instance at 0x82e8b2c>
>>> exec "def f(self): return 15"  # dynamically create the string
>>> setattr(c,'func',f)
>>> c().func()
15

If you describe the actual problem we might be able to give you 
a better solution than "compilation at runtime". 

regards,

    holger




More information about the Python-list mailing list