Why would you use metaclasses?

Technology CommunityCategory: PythonWhy would you use metaclasses?
VietMX Staff asked 3 years ago

Well, usually you don’t. The main use case for a metaclass is creating an API. A typical example of this is the Django ORM.

It allows you to define something like this:

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

And if you do this:

guy = Person(name='bob', age='35')
print(guy.age)

It won’t return an IntegerField object. It will return an int, and can even take it directly from the database.

This is possible because models.Model defines __metaclass__and it uses some magic that will turn the Person you just defined with simple statements into a complex hook to a database field.

Django makes something complex look simple by exposing a simple API and using metaclasses, recreating code from this API to do the real job behind the scenes.