-
Notifications
You must be signed in to change notification settings - Fork 87
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support Generic
structs
#193
Comments
Thanks for opening this issue. This is definitely in scope for
That'd work, but we also expose import msgspec
def GenericStruct(T):
return msgspec.defstruct("MyStruct", [("value", T)])
decoder = msgspec.json.Decoder(GenericStruct(int))
assert decoder.decode(b'{"value": 1}').value == 1 |
@MaximZayats, can you comment more on your use case for generic structs? I'm starting to look into this, but having a motivating example would be useful. |
@jcrist, sure. I am currently working on fast python class Request(Struct):
id: int | str | None = None
method: str
params: Raw = Raw() # this field can be generic, but in my case `Raw` is more suitable
jsonrpc: str = "2.0"
class SuccessfulResponse(Struct):
id: int | str | None = None
result: Any # <- this field can be generic
jsonrpc: str = "2.0" And actually I found out, that generic structs in my case is not necessary :) Btw, pydantic has some examples like mine: |
I am looking for the same functionality because I want to inherit a base class: It is not the nicest example but the idea is like this:
This means I can attach new fields in the subclass and use the ones from the parent class. But also assume there is always a value field but the type could change which can be checked by Mypy if I create a certain object instance. Is this somewhere on the roadmap to be implemented? |
This is definitely something that's in scope, and that I want to support. It's just not done yet. |
My use case is the following. class BaseMessage(Struct, tag_field="msg_type", tag=str.lower):
pass
class WrapperMessage(BaseMessage):
to: str
msg: T # <- this is generic I cannot use I am relying heavily on type hinting to make sure only the appropriate messages are passed, so having a support for Generics out of the box would be nice. Last alternative for me would be to use |
Having same issue. I'm trying to define class MyList (Struct, Generic[A]):
head: A
tail: Optional[MyList[A]] But error occurs:
So, what can I do to support this feature? |
I'll give another use case where Generic structs would be very useful. Let's say that we have some sort of tagged structures returned by an API: class ThingOne(Struct, tag="one"):
value: int
class ThingTwo(Struct, tag="two"):
label: str and the API uses a generic envelope for returning lists of tagged values such that it can be expressed as: class ThingList(Struct, tag="list"):
data: list[ThingOne | ThingTwo]
total_things: int This works fine as is but loses a lot of type information and validation power when dealing with APIs that have a known return type: def get_thing_ones() -> ThingList:
thing_list = msgspec.json.decode(get_data(), type=ThingList)
return thing_list
def use_thing_ones() -> ...:
thing_ones_list = get_thing_ones()
thing_ones = cast(list[ThingOne], thing_ones_list.data) With generics, especially if validated on decode, the above could be expressed as: class ThingList(GenericStruct[T], tag="list"):
data: list[T]
total_things: int
def get_thing_ones() -> ThingList[ThingOne]:
thing_list = msgspec.json.decode(get_data(), type=ThingList[ThingOne]):
return thing_list
def use_thing_ones() -> ...:
thing_ones_list = get_thing_ones()
thing_ones = thing_ones_list.data saving a lot of casting and making the return types much clearer on reading method signatures |
Hi, just stumbled in this exact issue... My 2, very similar, use cases:
Adding the support for generics would be really awesome! |
Support for generic structs has been merged in #386 🚀 🚀. I'm going to add generics support for If anyone is interested, I'd love it if someone could install from the main branch (https://jcristharif.com/msgspec/install.html#installing-from-github) and try things out. I believe our test suite should cover all the possible edge cases, but if there are bugs it'd be nice to catch 'em now before the release. |
@jcrist , I can confirm that generic structs are working correctly for me in the current |
Hi!
Is it possible to add support for generics ?
Example:
If I understand correctly, at the moment the only way to create a generic structure is to use
type()
:The text was updated successfully, but these errors were encountered: