msgspec
msgspec copied to clipboard
Inherit __init_subclass__ args to subclass
I'm using msgspec for API response validation, so I wrote this:
class Response(Struct, frozen=True, kw_only=True):
pass
So all of the responses should be created by passing kwargs, and they can't be modified by accident.
But when I use this:
class SomeResponse(Response):
field: int
test = SomeResponse(1) # successed, oops...
Seems that args for __init_subclass__ can't be inherited.
So how can I do to implement this? Should I use metaclass or something else?
Currently I'm using this:
RESPONSE_CONFIG = {
"kw_only": True,
"frozen": True
}
class SomeResponse(Struct, **RESPONSE_CONFIG):
field: int
It works, but ugly and I can easily forget to add CONFIG, which result in non-restricted response struct.
From the docs:
Note that the kw_only setting only affects fields defined on that class, not those defined on base or subclasses.
So this is expected behaviour.