
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?
Category
27 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.

First let us recall which data types exist in Python, then learn how to convert between them using type conversion functions.

Method Operations = Method Wrapper. An in-depth look at str object methods and method-wrappers in Python.

In the topics covered so far we never talked about errors, how to catch them, or how to continue execution based on the error encountered. This is an important topic and you will learn it here.