Re:Problems once solved by a metaclass can be solved by __in...
by Macha on Wednesday January 05, 2022 @02:25PM
(#29813650)
One use is for e.g. binding of database models for an ORM.
class FooModel(metaclass=Base):
x = Field(type=int, primary_key=True)
y = Field(type=reference(BarModel))
The Base metaclass will set it up to implement methods like save() by inheriting from parent classes, but it would also be nice for the library to have a list of all model types without the library user having to call a method like FooORM.register_type(FooModel). So the metaclass is being used in these classes to build up a dictionary of models when the class definition is encountered.
The metaclass is basically a class that itself builds classes, which means it can be syntactically convoluted.
However, with __init_subclass__ you can write a thing that looks like a regular class with regular parent methods, but instead just gets a method called each time the interpreter encounters a new subclass, which lets you do things like build up that dictionary for your ORM.
The metaclass is basically a class that itself builds classes, which means it can be syntactically convoluted.
However, with __init_subclass__ you can write a thing that looks like a regular class with regular parent methods, but instead just gets a method called each time the interpreter encounters a new subclass, which lets you do things like build up that dictionary for your ORM.