Jump to content

Python Programming/Metaclasses

From Wikibooks, open books for an open world


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

Python3

[edit | edit source]

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.[1] Then there is the __new__ method that is called to create new instances of that class. [2]

The type Metaclass

[edit | edit source]

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

>>> type(object)
<type 'type'>
>>> type(int)
<type 'type'>
>>> type(list)
<type 'type'>

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.

>>> type(type)
<type 'type'>

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:

>>> class MyClass(BaseClass):
...     attribute = 42

Could also be written as:

>>> MyClass = type("MyClass", (BaseClass,), {'attribute' : 42})

Metaclasses

[edit | edit source]

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

class CustomMetaclass(type):
    def __init__(cls, name, bases, dct):
        print("Creating class %s using CustomMetaclass" % name)
        super(CustomMetaclass, cls).__init__(name, bases, dct)

class BaseClass(metaclass=CustomMetaclass):
    pass

class Subclass1(BaseClass):
    pass

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

[edit | edit source]

References

[edit | edit source]


Clipboard

To do:
[Incomplete] (see Putting Metaclasses to Work, Ira R. Forman, Scott H. Danforth?)