jcrist · GitHub

added 4 commits

January 14, 2023 21:39
Previously a union `Union[str, bytes]` was support for `msgpack` and
forbidden for `JSON` due to ambiguities in parsing. This is kind of a
weird union to support in real-world APIs. Since it simplifies the code,
we now apply this restriction for all protocols.
To provide parity between the keyword arguments to `to_builtins` and
`from_builtins`, we rename `passthrough` to `builtin_types`. No
functionality is changed, only the keyword name.
This adds a new function for converting messages composed of simple
builtin types to validated messages (potentially composed of more
complex types). This is the mirror of `msgspec.to_builtins`. While this
may be used directly by users, it's mainly intended to be useful for
wrapping other serialization protocols not natively support by msgspec
(e.g. YAML, TOML, ...).
Messages composed of the following input types are supported:
- `None`
- `bool`
- `int`
- `float`
- `str`
- `bytes`
- `bytearray`
- `datetime.datetime`
- `datetime.date`
- `datetime.time`
- `uuid.UUID`
- `list`
- `tuple`
- `dict`
`from_builtins` can map these builtin types to the full set of types
support by msgspec. For example:
```python
In [1]: import msgspec
In [2]: class Example(msgspec.Struct):
   ...:     x: set[int]
   ...:     y: bytes
   ...:
In [3]: msg = {'x': [1, 2, 3], 'y': 'AQI='}
In [4]: msgspec.from_builtins(msg, Example)
Out[4]: Example(x={1, 2, 3}, y=b'\x01\x02')
```

@jcrist

@jcrist jcrist changed the title [WIP] Add msgspec.from_builtins Add msgspec.from_builtins

Jan 17, 2023

@jcrist

@jcrist

@jcrist

@jcrist

@jcrist

Closed

Read the original on github.com ↗