jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.3k stars 67 forks source link

Inherit __init_subclass__ args to subclass #607

Open FHU-yezi opened 10 months ago

FHU-yezi commented 10 months ago

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.

wikiped commented 7 months ago

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.