Dynamically creating classes - Python

Solution 1:

You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:

CommentForm = type("CommentForm", (Form,), { 
    'name': forms.CharField(),
    ...
})

It works with new-style classes. I am not sure, whether this would also work with old-style classes.

Solution 2:

Classes can be defined almost anywhere.

def newclass(val):
  class C(object):
    def __str__(self):
      return str(val)
  return C

MyClass = newclass(5)
m = MyClass()
print str(m)