
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
61 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.

As you know, Django comes with a user model that has certain properties — name, last name, email, password, etc. While these fields save the day in most cases, sometimes they're not enough. Depending on the project you're building, users may need to have more properties. That's what we'll achieve by extending the user model.

Everyone uses this part of Django. Even those who have never used Django and are just starting to learn it use this area first — they open a console from the project directory and immediately start a new project to begin coding.

In this post, instead of writing CSS for the page design, I'll use a front-end framework called Uikit. The code I use here comes from a project called Eatingword that I'm developing to keep my Django skills fresh and learn new things.