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

### The type Metaclass

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

``` python
>>> 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.

``` python
>>> 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:

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

Could also be written as:

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

### 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

``` python
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

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

### References


[^1]: <http://www.python.org/dev/peps/pep-3115/>

[^2]: <http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/>
