Tuesday, March 29, 2005

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()
woof
>>>
>>> def meow(self):
... print `self`
... print "meow"
...
>>> Page.meow = meow
>>>
>>> Page().meow()
<__main__.page>
meow

6 comments:

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...

hello!
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)
4
5 class MetaClass(MyParentClass):
6 """ here some 'static' stuff - func, attr etc"""
7
8 MetaClass.foo = 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.

e.g.

class ClsFactory(type):
def __new__(mcls, name, bases, attrs):
#here we describe the different stuff of our new class
def foo(obj):
print 'foo'
#assign
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 )

Shannon -jj Behrens said...

Great comment. Thanks!

Nathaniel Higgins said...

Best Way:

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

Shannon -jj Behrens said...

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

Nice ;)