Create Python Class On The Fly

I just found a cool trick in python to create a class dynamically on the fly without creating the class definition.

The story behind this, I’m using Django in my project and I need to create serializer class dynamically based on user’s input. Here is how I solving my problem by creating serializer class on the fly.

def serializer_factory(list_context):
    fields = {}
    for i in list_context:
        fields[i] = serializers.CharField(required=True)
    GeneratedClass = type("SerializerFactory", (serializers.Serializer,), fields)
    return GeneratedClass

And here is how I used it.

context = ['name', 'address', 'current_location']
PeopleClass = serializer_factory(context)
serializer = PeopleClass(
code above equivalent with.

class SerializerFactory(serializers.Serializer):
    name = serializers.CharField(required=True)
    address = serializers.CharField(required=True)
    current_location = serializers.CharField(required=True)

“type” in python commonly uses in meta programming, and here is the detail for creating class using this keyword.

type("", (), {})

1. The first String argument is for defining class name.
2. Second argument is tuple to define your base class.
3. Third argument is dictionary for defining class property.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s