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

Support custom builtin_types in to_builtins #517

Merged
merged 1 commit into from
Aug 15, 2023

Conversation

jcrist
Copy link
Owner

@jcrist jcrist commented Aug 15, 2023

This adds support for "custom" builtin_types in to_builtins. This is useful when wrapping a protocol like bson that has protocol specific types like ObjectId that you'll want to pass through unchanged.

For example, to support passing bson.ObjectId through msgspec.to_builtins:

In [1]: import msgspec, bson

In [2]: class Point(msgspec.Struct):
   ...:     _id: bson.ObjectId
   ...:     x: int
   ...:     y: int
   ...:

In [3]: obj = Point(bson.ObjectId(), 1, 2)

In [4]: obj
Out[4]: Point(_id=ObjectId('64dad4a21ffe3dbdae50a48e'), x=1, y=2)

In [5]: msg = msgspec.to_builtins(obj, builtin_types=(bson.ObjectId,))

In [6]: msg
Out[6]: {'_id': ObjectId('64dad4a21ffe3dbdae50a48e'), 'x': 1, 'y': 2}

In [7]: msgspec.convert(msg, type=Point)
Out[7]: Point(_id=ObjectId('64dad4a21ffe3dbdae50a48e'), x=1, y=2)

Fixes #516.

This adds support for "custom" `builtin_types` in `to_builtins`. This is
useful when wrapping a protocol like `bson` that has protocol specific
types like `ObjectId` that you'll want to pass through unchanged.

For example, to support passing `bson.ObjectId` through
`msgspec.to_builtins`:

```python
In [1]: import msgspec, bson

In [2]: class Point(msgspec.Struct):
   ...:     _id: bson.ObjectId
   ...:     x: int
   ...:     y: int
   ...:

In [3]: obj = Point(bson.ObjectId(), 1, 2)

In [4]: obj
Out[4]: Point(_id=ObjectId('64dad4a21ffe3dbdae50a48e'), x=1, y=2)

In [5]: msg = msgspec.to_builtins(obj, builtin_types=(bson.ObjectId,))

In [6]: msg
Out[6]: {'_id': ObjectId('64dad4a21ffe3dbdae50a48e'), 'x': 1, 'y': 2}

In [7]: msgspec.convert(msg, type=Point)
Out[7]: Point(_id=ObjectId('64dad4a21ffe3dbdae50a48e'), x=1, y=2)
```
@jcrist jcrist merged commit a19a8b6 into main Aug 15, 2023
7 checks passed
@jcrist jcrist deleted the to-builtins-custom-builtins branch August 15, 2023 01:48
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.

Support for ObjectId in to_builtins/convert
1 participant