Basic Metaclasses

suggest change

When type is called with three arguments it behaves as the (meta)class it is, and creates a new instance, i.e. it produces a new class/type.

Dummy = type("OtherDummy", (), {"x": 1})
Dummy.__class__              # <class 'type'>
Dummy().__class__.__class__  # <class 'type'>

It is possible to subclass type to create a custom metaclass.

class CustomType(type):
    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)

        # perform custom initialization...
        cls.__custom_attribute__ = 2

Now, we have a new custom metaclass which can be used to create classes in the same manner as type.

MyDummy = CustomType("MyDummy", (), {"x": 2})
MyDummy.__class__              # <class '__main__.CustomType'>
MyDummy().__class__.__class__  # <class '__main__.CustomType'>
MyDummy.__custom_attribute__   # 2

When we create a new class using the class keyword the metaclass is by default chosen based on the base classes.

>>> class Foo:
...     pass

>>> type(Foo)
<class 'type'>

Use the metaclass keyword argument to specify a metaclass:

class MyDummy(metaclass=CustomType):
    pass
type(MyDummy)  # <class '__main__.CustomType'>

Any keyword arguments other than metaclass in the class declaration are passed to the metaclass. A metaclass that accepts them must implement a compatible __new__ or __init__ method.

Read this in-depth description of python meta-classes for more details.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents