Best way to create a class dynamically on the fly?

Gerhard Häring gerhard.haering at gmx.de
Sat Sep 28 22:21:10 EDT 2002


Robert Oschler wrote in comp.lang.python:
> 
> "Evan" <evan at 4-am.com> wrote in message news:3D96511D.2040407 at 4-am.com...
>> Robert Oschler wrote:
>> > What is the best way to create a Python class dynamically at runtime?
>>
>> ALL Python classes are created dynamically at runtime.  The following is
>> not a declaration in the sense that you're accustomed to from C/C++, it
>> is normal code executed when the containing file is run (or imported):
>>
>> class Foo:
>>    def meth1(self):
>>      return "I am a method"
>>
><snip>
> 
> Evan,
> 
> I understand but what I'm after is building the class itself dynamically,
> akin to the way you can manufacture a prolog predicate on the fly.  For
> example,  if wanted to create a class whose name was provided in a string
> variable called ClassName, at runtime.  Or did I misunderstand your reply?

You can still do that by calling whatever is the equivalent of 'exec'
at the C-level.

One other possibility, which I've used in Python, but not from C or
C++, yet is using the 'new' module to dynamically create classes at
runtime.

Here's a simplistic example, that should be relatively easy to convert
to C:

    import new

    def make_class(name):
        cls = new.classobj(name, (), {})
        return cls

    cls = make_class("foo")
    obj = cls()

The 'new' module doesn't have a C API, so you'll probably have to
import it and call the 'classobj' method using PyObject_CallObject

-- Gerhard



More information about the Python-list mailing list