Dynamically creating classes – Python

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.

Leave a Comment