Skip to main content

Python: Create a new class on the fly

At PyCon, Alex Martelli mentioned that you could create a class on the fly using the type function. Previously, I probably would have used the exec function. I feel like such a dork:
>>> class Template(object): # Must be a new-style class.
... def bark(self):
... print "woof"
>>> Page = type("Page", (Template,), {})
>>> Page().bark()
>>> def meow(self):
... print `self`
... print "meow"
>>> Page.meow = meow
>>> Page().meow()


Ian Bicking said…
The "new" module has also been available for this sort of thing for a while -- also for creating module objects and other things.
roma said…
There is a several method to create python classes "on the fly", but I prefer writing a function, which create a new class with given params, like than:
1 def MetaFunc(cls_name, key, value):
2 def foo(obj):
3 print 'new class with key-%s and value %s'%(key, value)
5 class MetaClass(MyParentClass):
6 """ here some 'static' stuff - func, attr etc"""
8 = foo #'dinamically' assign the function
9 setattr(cls_name,key,value) #assign the attr
10 return MetaClass #return the meta classobj

I attemted to use a "type" class for instancing a new class from it, but for me it's not so handy.


class ClsFactory(type):
def __new__(mcls, name, bases, attrs):
#here we describe the different stuff of our new class
def foo(obj):
print 'foo'
attrs['foo'] = foo
return super(ClsFactory,mcls).__new__(mcls, name, bases, attrs)

#here is instancing from type object and inheritence from paren class (if needed)
class HelloClass(MyParentClass):
__metaclass__ = ClsFactory

p.s. It's very interesting blog! )

best regards, Roman Kabiev
Рома said…
upss!,I was not authorized when wrote the prior post )
Great comment. Thanks!
Best Way:

c = type('', (), {})
> c = type('', (), {})

Nice ;)