Before I begin the ceremony of Python worship once again, I feel obliged to warn you that dynamic class creation is not a frequently used programming pattern. The reason lies in the logic behind class creation. In reality, classes follow objects, not the other way round. You have a couple of objects which are similar yet there are noticeable differences too. I know it sounds kind of oxymoronic. Let me give an example.

Writing code for the objects shown above would be a repetitive task, with minor variation.

In such a situation, one takes the common properties of all the objects and creates a class with those. Here, we will create a class called ellipse to map all the four objects, as a circle is a special case of an ellipse. Equation of an ellipse with centre at origin is:


If you make a=b you get the equation of a circle :

x2 + y2 = a2

So the long and short of it is that we, as software designers, always try to generalize things as much as possible. That leads to less coding. So dynamic class creation is a bad idea. You don't want to increase the number of classes by creating some dynamically! An exception to the rule is the scenario where you are mapping a unique system on Python. The other system comes with its baggage of hundreds of types, which, for obvious reasons, you would like to assign to classes in Python. An XML document repository containing documents of different types is one good example. A database containing hundreds of tables is another good and more ubiquitous one. We will continue with the second example, as the other one requires pretty extensive coding; and in the process of frenzied coding, the core point is lost. I am connecting to an Oracle EBS database. It has got so many tables that you are spoilt for choice!

Let us select a smaller one, with less than ten columns.

The point of picking up the table with the shortest name is to avoid excessive typing. So MTL ACTIONS_TL is our table.

It has this structure:

The function mentioned below would dynamically create a Python class and return

Finally, upon execution, we indeed get a new, dynamically created class: