Skip to content

Commit 84542a5

Browse files
john-bodleylovasoa
andauthored
[README] Add documentation about Union types (lovasoa#184)
* [README] Update README.md to address issue lovasoa#183 * Update README.md * fix typo in README.md Co-authored-by: Ophir LOJKINE <pere.jobs@gmail.com>
1 parent fa6c289 commit 84542a5

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,32 @@ PersonSchema = marshmallow_dataclass.class_schema(Person)
9292

9393
The type of your fields must be either basic
9494
[types supported by marshmallow](https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.Schema.TYPE_MAPPING)
95-
(such as `float`, `str`, `bytes`, `datetime`, ...), or other dataclasses.
95+
(such as `float`, `str`, `bytes`, `datetime`, ...), `Union`, or other dataclasses.
96+
97+
### Union (de)serialization coercion
98+
99+
Typically the Union type; `Union[X, Y]` means—from a set theory perspective—either `X` or `Y`, i.e., an unordered set, howevever the order of the sub-types defines the precedence when attempting to ether deserialize or serialize the value per [here](https://github.com/lovasoa/marshmallow_dataclass/blob/master/marshmallow_dataclass/union_field.py).
100+
101+
For example,
102+
103+
```python
104+
from typing import Union
105+
106+
from dataclasses import dataclass
107+
108+
109+
@dataclass
110+
class Person:
111+
name: str
112+
age: Union[int, float]
113+
114+
115+
PersonSchema = marshmallow_dataclass.class_schema(Person)
116+
PersonSchema().load({"name": "jane", "age": 50.0})
117+
# => Person(name="jane", age=50)
118+
```
119+
120+
will first (sucessfully) try to coerce `50.0` to an `int`. If coercion is not desired the `Any` type can be used with the caveat that values will not be type checked without additional [validation](https://marshmallow.readthedocs.io/en/stable/marshmallow.validate.html).
96121

97122
### Customizing generated fields
98123

0 commit comments

Comments
 (0)