Skip to content

Add attributes option to from_builtins - #419

Merged
jcrist merged 1 commit into
mainfrom
from-builtins-attributes
May 30, 2023
Merged

Add attributes option to from_builtins#419
jcrist merged 1 commit into
mainfrom
from-builtins-attributes

Conversation

@jcrist

@jcrist jcrist commented May 30, 2023

Copy link
Copy Markdown
Member

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

jcrist commented May 30, 2023

Copy link
Copy Markdown
Member Author

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
Copy Markdown

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

@jcrist

jcrist commented Jul 14, 2023

Copy link
Copy Markdown
Member Author

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