Reading preferences
Concept

Metaclasses and Introspection

Inspect a class and see when its metaclass validates its definition.

python, metaclasses, introspection, reflection, inspect

Classes are objects too

An instance is created from a class. A class is itself an object, normally created by type. A metaclass customises class creation; it is not needed for most ordinary classes.

Python illustration

import inspect

class RequireLabel(type):
    def __new__(meta, name, bases, namespace):
        if "label" not in namespace:
            raise TypeError("class must define label")
        return super().__new__(meta, name, bases, namespace)

class Book(metaclass=RequireLabel):
    label = "book"

    def describe(self, title):
        return f"{self.label}: {title}"

print(Book.label)
print(inspect.signature(Book.describe))
print(Book().describe("Read"))

Prepared output — not live execution:

book
(self, title)
book: Read

The class body builds a namespace. The metaclass checks that namespace and then delegates to type to create Book. An omitted label in this specific example raises TypeError at class creation, even if a base class has a label: the rule explicitly checks the new namespace.

See the reasoning

From class body to inspection

See when the metaclass checks the namespace before Book exists. This is a prepared demonstration, not live code execution.

Run the class body

Class creation and inspection
  1. Namespacelabel; describeCurrent focus
  2. Metaclasscheck pending
  3. Classnot created
  4. Inspectionpending

The body creates a namespace containing label and describe.

Observe without assuming safety

Introspection examines runtime objects: type, isinstance, vars, and inspect.signature are common tools. Reflection can also influence behaviour based on those observations. Ordinary getattr or hasattr may invoke descriptors or custom lookup; do not assume inspection is side-effect-free. inspect.getattr_static avoids dynamic attribute lookup, but may return the descriptor itself rather than the computed value. Prefer simpler mechanisms such as class decorators or __init_subclass__ before a metaclass when they meet the requirement.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What does a metaclass primarily construct?
2. When does the example's metaclass validate a class?
3. What can inspect.signature help reveal?
4. Can ordinary getattr invoke code while inspecting an object?

References and further reading