Editor

Build a Field-Discovery 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 simplified ORM-style system:

1. A Field class with __init__(self, field_type) that stores the type, and a __repr__ that returns 'Field(<type_name>)' (e.g. 'Field(str)')

2. A metaclass ModelMeta that collects all Field instances into a _fields dict and also stores a _field_names list (sorted alphabetically)

3. A Model base class using the metaclass

4. A Product model with fields: name (str), price (float), quantity (int)

Print Product._field_names.

# Build the Field class, ModelMeta metaclass, Model base, and Product model

More Metaclass exercises

All Python exercises · 50 practice problems · Metaprogramming quiz