Python Programming/Metaclasses

In Python, classes are themselves objects. Just as other objects are instances of a particular class, classes themselves are instances of a metaclass.

Python3
The Pep 3115 defines the changes to python 3 metaclasses. In python3 you have a method __prepare__ that is called in the metaclass to create a dictionary or other class to store the class members. Then there is the __new__ method that is called to create new instances of that class.

The type Metaclass
The metaclass for all standard Python types is the "type" object.

Just like list, int and object, "type" is itself a normal Python object, and is itself an instance of a class. In this case, it is in fact an instance of itself.

It can be instantiated to create new class objects similarly to the class factory example above by passing the name of the new class, the base classes to inherit from, and a dictionary defining the namespace to use.

For instance, the code:

Could also be written as:

Metaclasses
It is possible to create a class with a different metaclass than type by setting the metaclass keyword argument when defining the class. When this is done, the class, and its subclass will be created using your custom metaclass. For example

This will print

Creating class BaseClass using CustomMetaclass Creating class Subclass1 using CustomMetaclass

By creating a custom metaclass in this way, it is possible to change how the class is constructed. This allows you to add or remove attributes and methods, register creation of classes and subclasses creation and various other manipulations when the class is created.

More resources

 * Wikipedia article on Aspect Oriented Programming
 * Unifying types and classes in Python 2.2
 * O'Reilly Article on Python Metaclasses