0Pricing
Python Academy · Lesson

Writing Custom Metaclasses

Use __new__ and __init__ in metaclasses to customize class creation.

Declaring a Metaclass

Pass metaclass=MyMeta in the class definition to use a custom metaclass. The metaclass must inherit from type.

class MyMeta(type):
    pass

class Foo(metaclass=MyMeta):
    pass

print(type(Foo))   # <class '__main__.MyMeta'>

Overriding __new__

__new__(mcs, name, bases, namespace) creates the class object. Use it to modify the namespace before the class is built.

class UpperAttrMeta(type):
    def __new__(mcs, name, bases, namespace):
        upper = {k.upper(): v for k, v in namespace.items()
                 if not k.startswith("_")}
        return super().__new__(mcs, name, bases, {**namespace, **upper})

class Config(metaclass=UpperAttrMeta):
    debug = True

print(Config.DEBUG)  # True

All lessons in this course

  1. How Python Classes Are Created
  2. Writing Custom Metaclasses
  3. Descriptors: __get__, __set__, __delete__
  4. __slots__ and Memory Optimization
← Back to Python Academy