
Register Classes in Python
Three ways to automatically register subclasses: metaclass __new__, __init_subclass__, and class decorator. Which one is more appropriate for which situation?
Tag
15 posts

Three ways to automatically register subclasses: metaclass __new__, __init_subclass__, and class decorator. Which one is more appropriate for which situation?

A dataclass-like structure built with a metaclass: automatic __slots__ derived from type annotations and runtime type validation inside __call__.

Automatically record every assignment in the class body using the metaclass __prepare__ method — discover the power of a customized namespace.

The implementation of the defineif library: a customized namespace via __prepare__ that silently defines or skips methods at class creation time based on a boolean condition.

Automatically generate __slots__ from __init__ parameters using a metaclass and co_names.

Writing `class Example: ...` and calling `type('Example', (), {...})` produce exactly the same result. Python transforms the class keyword into a type() call behind the scenes.