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

Add attributes option to from_builtins #419

Merged
merged 1 commit into from
May 30, 2023
Merged

Conversation

jcrist
Copy link
Owner

@jcrist jcrist commented May 30, 2023

This adds a new attributes option to from_builtins. If enabled, arbitrary objects may be coerced to Struct/dataclasses/attrs types by extracting attributes from the input object matching fields in the output type. One use case is converting database query results (ORM or otherwise) to msgspec structured types.

Fixes #416.

This adds a new `attributes` option to `from_builtins`. If enabled,
arbitrary objects may be coerced to `Struct`/`dataclasses`/`attrs` types
by extracting attributes from the input object matching fields in the
output type. One use case is converting database query results (ORM or
otherwise) to msgspec structured types.
@jcrist jcrist merged commit 9a8301d into main May 30, 2023
@jcrist jcrist deleted the from-builtins-attributes branch May 30, 2023 15:23
@jcrist
Copy link
Owner Author

jcrist commented May 30, 2023

A quick example:

import msgspec


class User(msgspec.Struct):
    name: str
    groups: list[str] = []
    email: str | None = None


class UserORM:
    """An example ORM-like input object"""
    def __init__(self, name, groups):
        self.name = name
        self.groups = groups
        # No `email` present on ORM object, default will be used when converting


data = [UserORM("alice", ["admin"]), UserORM("ben", [])]

converted = msgspec.from_builtins(data, list[User], attributes=True)
print(converted)
#> [User(name='alice', groups=['admin'], email=None), User(name='ben', groups=[], email=None)]

@dmckeone
Copy link

I've been playing with this a little and it's been working well for every case I've tried.

@jcrist
Copy link
Owner Author

jcrist commented Jul 14, 2023

Glad to hear it!

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

Successfully merging this pull request may close these issues.

from_builtins, but for objects? (e.g instantiate from SQLAlchemy models)
2 participants