msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Inherit __init_subclass__ args to subclass

Open FHU-yezi opened this issue 1 year ago • 1 comments

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.

FHU-yezi avatar Dec 09 '23 15:12 FHU-yezi

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.

wikiped avatar Feb 20 '24 16:02 wikiped