jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.3k stars 67 forks source link

`defstruct` with `default_factory ` and/or `FieldInfo` #580

Closed alexei closed 10 months ago

alexei commented 11 months ago

Description

Currently defstruct offers no way of declaring a field with a default_factory, but this could be useful when e.g. defining structs from dataclasses. Is there any chance of supporting this?

Or maybe even with FieldInfo à la:

defstruct(
    "Foo",
    (
        ("field1", FieldInfo(default="val1", ...)),
        ("field2", FieldInfo(default_factory=datetime.now, ...)),
        ...
    ),
)
jcrist commented 11 months ago

This is currently supported by passing a msgspec.field as the third item in a field tuple:

from datetime import datetime

from msgspec import defstruct, field

Foo = defstruct(
    "Foo",
    [
        ("field1", str, "val1"),
        ("field2", datetime, field(default_factory=datetime.now)),
    ],
)

print(Foo())
#> Foo(field1='val1', field2=datetime.datetime(2023, 11, 6, 22, 47, 19, 814065))

Is there a way this could be made clearer in the docs? If so, PRs welcome!

jcrist commented 10 months ago

Closing as stale/resolved.

alexei commented 10 months ago

I opened a PR, see https://github.com/jcrist/msgspec/pull/586