Skip to content

Working example showing some of the power of python3 metaclasses

Notifications You must be signed in to change notification settings

pwhipp/python_metaclass

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 

Repository files navigation

Python3 Metaclass Example

We need something a little meaningful so the example consists of some simple models in a class heirarchy and an associated heirarchy of model serializers1.

The first commit shows how serializers need to be accessed for the model classes in order to serialize/deserialize model data.

Maintaining the serializer_class_map quickly becomes cumbersome.

We could define a decorator e.g.

@SetModelClass(ModelSerializer)
class ModelSerializer(Serializer):
    ...

but this is repeating the association because its already present in the Meta (so that the serializer can create new models)

We could add a serializer_class field to the models but this is coupling the serializers to the models in an undesirable way. We want to keep the serialization concern to our serializers.

So how about a metaclass?

If we specify a metaclass for our serializers we can update the serializer_class_map whenever we create a new serializer class.

This commit shows the use of the MappedSerializerClass to maintain the serializer_class_map. This separates out the mapping concern and is a pretty good solution.

Footnotes

1 This is a loose abstraction of django models and the django rest framework.

About

Working example showing some of the power of python3 metaclasses

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages