Support `Generic` structs
See original GitHub issueHi! Is it possible to add support for generics ?
Example:
from typing import TypeVar, Generic, Any
import msgspec
T = TypeVar("T", bound=Any)
class MyStruct(msgspec.Struct, Generic[T]):
value: T
decoder = msgspec.json.Decoder(MyStruct[int])
assert decoder.decode(b'{"value": 1}').value == 1
If I understand correctly, at the moment the only way to create a generic structure is to use type()
:
def GenericStruct(type_: Type) -> Type[msgspec.Struct]:
return type( # type: ignore
"MyStruct",
(msgspec.Struct,),
{
"__annotations__": {
"value": type_,
},
}
)
decoder = msgspec.json.Decoder(GenericStruct(int))
assert decoder.decode(b'{"value": 1}').value == 1
Issue Analytics
- State:
- Created a year ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top Results From Across the Web
How to use Golang generics with structs | by Tiago Temporin
This week, while I was looking through the Golang source code, I found an example of how to create structs using generics.
Read more >An Introduction to Generics in Go | by Na'aman Hirschfeld
Generics offer a powerful and simple way to create generic functions, interfaces and struct methods. They allow a reduction in boilerplate and ...
Read more >Generic struct initialization with… | Apple Developer Forums
Hello,. I'd like to have a generic struct that can be initialized with some data whose type is constrained but unknown up to...
Read more >Generic Structs with Go - Stack Overflow
Starting with Go 1.18, you can define generic types: type Model[T any] struct { Data []T }. A generic type must be instantiated...
Read more >Generics are the Generics of Go | Capital One
Introducing Generics in Go · Place ' [T any]' after the type name and before the struct literal. T is the name we'll...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This is definitely something that’s in scope, and that I want to support. It’s just not done yet.
msgspec
is a side hobby project for me, so features only get added when I have free time. I can’t give you an estimate on when this will be resolved, but hopefully sometime in the next few months.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?