Dynamically creating classes
Metaclasses are the factories that create new classes in Python. In fact, even though you may not be aware of it, Python will always execute the type
metaclass whenever you create a class.
A few common examples where metaclasses are used internally are abc
(abstract base classes), dataclasses
, and the Django framework, which heavily relies on metaclasses for the Model
class.
When creating classes in a procedural way, the type
metaclass is used as a function that takes three arguments: name
, bases
, and dict
.name
will become the __name__
attribute, bases
is the list of inherited base classes and will be stored in __bases__
, and dict
is the namespace dictionary that contains all variables and will be stored in __dict__
.
It should be noted that the type()
function has another use as well. Given the arguments documented above, it will create a class with those specifications. Given a single argument with the instance of a class (for example, type...