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

defstruct with default_factory and/or FieldInfo #580

Closed
alexei opened this issue Nov 6, 2023 · 3 comments
Closed

defstruct with default_factory and/or FieldInfo #580

alexei opened this issue Nov 6, 2023 · 3 comments

Comments

@alexei
Copy link
Contributor

alexei commented Nov 6, 2023

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
Copy link
Owner

jcrist commented Nov 7, 2023

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
Copy link
Owner

jcrist commented Nov 17, 2023

Closing as stale/resolved.

@alexei
Copy link
Contributor Author

alexei commented Nov 18, 2023

I opened a PR, see #586

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

2 participants