Skip to content
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

Structs with nested array_like Structs asdict #830

Open
mledezma-r7 opened this issue Mar 31, 2025 · 0 comments
Open

Structs with nested array_like Structs asdict #830

mledezma-r7 opened this issue Mar 31, 2025 · 0 comments

Comments

@mledezma-r7
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant