2 ms·
More generically, Metaclasses are primarily useful when using (abusing?) the Python type system to represent other type systems. The most common example of this
by enragedcacti 5y ago
More generically, Metaclasses are primarily useful when using (abusing?) the Python type system to represent other type systems. The most common example of this is ORMs like SQLAlchemy, where the Python type system is used to represent tables in a relational database.
Another example is the builtin "Typing" module where the type system is used to provide a language for representing itself. "Union" itself is a type, and metaclasses allow you to set "__getitem__" on the "Union" type such that Union[Int|Str] is valid and represents a new type. Not that I don't know if metaclasses are actually used to build this system internally, but you could use it for many of the features implemented by Typing.
There are alternative ways to go about doing that because Python is so flexible, but IMO metaclasses (or __init_subclass__ as seen in this post) are the least "magic" of the magic ways to tackle problems like these.
- contravariant 5y agoYou got me curious so I looked it up. Apparently in Cpython 'Union' is not a class itself, but is a special object of type _SpecialForm, which is created by using _SpecialForm as a decorator on a function 'Union' which returns the actual union type given a set of parameters. Interestingly _SpecialForm uses a mixin _Final to prevent subclassing. This mixin is made using __init_subclass__