-
Notifications
You must be signed in to change notification settings - Fork 124
Open
Description
Question
Hey folks, I went over #594 because of the same assumptions.
I was expecting asdict to work on nested Structs, at least as an option.
This is where I'm struggling:
import msgspec
class Dog(msgspec.Struct, array_like=True):
name: str
age: int
class Owner(msgspec.Struct):
name: str
dogs: list[Dog]
owner = Owner('A dog owner', [Dog('Doggie', 2), Dog('Max', 1)])
msgspec.structs.asdict(owner)
>> {'name': 'A dog owner', 'dogs': [Dog(name='Doggie', age=2), Dog(name='Max', age=1)]}
msgspec.to_builtins(owner)
>> {'name': 'A dog owner', 'dogs': [['Doggie', 2], ['Max', 1]]}
I need to come up with the following:
>>> {'name': 'A dog owner', 'dogs': [{'name': 'Doggie', 'age': 2}, {'name': 'Max', 'age': 1}]}
I tried working around the issue with the following, but most of the performance gains vanish.
def asdict(obj):
if isinstance(obj, msgspec.Struct):
return asdict(msgspec.structs.asdict(obj))
if isinstance(obj, dict):
return {key: asdict(value) for key, value in obj.items()}
if isinstance(obj, list):
return [asdict(item) for item in obj]
return obj
Is there any plan to support the nested structs this way in asdict in the short term? or can you guys think of a good workaround? Thank you
Metadata
Metadata
Assignees
Labels
No labels