msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

`to_builtins` function converts a `Struct` object without default values

Open luwqz1 opened this issue 1 year ago • 0 comments

import msgspec


class User(msgspec.Struct, omit_defaults=True):
    id: int
    name: str
    city: str = msgspec.field(default="Aurora")


user = User(id=1, name="John")
print(user)  # User(id=1, name='John', city='Aurora')
print(msgspec.to_builtins(user))  # {'id': 1, 'name': 'John'}

user2 = msgspec.json.decode(b'{"id":2,"name":"Alex"}', type=User)
print(user2)  # User(id=2, name='Alex', city='Aurora')
print(msgspec.to_builtins(user2))  # {'id': 2, 'name': 'Alex'}

luwqz1 avatar Oct 15 '24 20:10 luwqz1