Skip to content

Support custom builtin_types in to_builtins#517

Merged
jcrist merged 1 commit intomainfrom
to-builtins-custom-builtins
Aug 15, 2023
Merged

Support custom builtin_types in to_builtins#517
jcrist merged 1 commit intomainfrom
to-builtins-custom-builtins

Conversation

@jcrist
Copy link
Copy Markdown
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
@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