Editor

Build a Validation Metaclass

Advanced · Write the code · from Python Metaclasses: Control How Classes Are Created

From the lesson: Python Metaclasses: Control How Classes Are Created

You already know that classes create objects. But have you ever wondered - what creates the classes themselves? In Python, the answer is metaclasses.

Read the lesson

Create a metaclass called DocstringRequired that raises a TypeError with the message "Class {name} must have a docstring" if any class using it (excluding the base class) does not have a __doc__ attribute or it is None.

Then create:

  • A base class Documented that uses the metaclass
  • A valid subclass GoodClass with a docstring 'I have docs'
  • Print GoodClass.__doc__ at the end.

    # Create the DocstringRequired metaclass
    # Create the Documented base class
    # Create GoodClass with a docstring

    More Metaclass exercises

    All Python exercises · 50 practice problems · Metaprogramming quiz