Debian Codegraph @

docs/data_model.md

raw
1 # Data model
2
3 *apischema* handles every class/type you need.
4
5 By the way, it's done in an additive way, meaning that it doesn't affect your types.
6
7 ### PEP 585
8 With Python 3.9 and [PEP 585](https://www.python.org/dev/peps/pep-0585/), typing is substantially shaken up; all container types of `typing` module are now deprecated.
9
10 apischema fully support 3.9 and PEP 585, as shown in the different examples. However, `typing` containers can still be used, especially/necessarily when using an older version.
11
12 ## Dataclasses
13
14 Because the library aims to bring the minimum boilerplate, it's built on the top of standard library. [Dataclasses](https://docs.python.org/3/library/dataclasses.html) are thus the core structure of the data model.
15
16 Dataclasses bring the possibility of field customization, with more than just a default value. In addition to the common parameters of [`dataclasses.field`](https://docs.python.org/3/library/dataclasses.html#dataclasses.field), customization is done with the `metadata` parameter; metadata can also be passed using PEP 593 `typing.Annotated`.
17
18 With some teasing of features presented later:
19
20 ```python
21 {!field_metadata.py!}
22 ```
23
24 !!! note
25 Field's metadata are just an ordinary `dict`; *apischema* provides some functions to enrich these metadata with its own keys (`alias("foo_bar")` is roughly equivalent to `{"_apischema_alias": "foo_bar"}) and use them when the time comes, but metadata are not reserved to *apischema* and other keys can be added.
26
27 Because [PEP 584](https://www.python.org/dev/peps/pep-0584/) is painfully missing before Python 3.9, *apischema* metadata use their own subclass of `dict` just to add `|` operator for convenience in all Python versions.
28
29 Dataclasses `__post_init__` and `field(init=False)` are fully supported. Implications of this feature usage are documented in the relative sections.
30
31 !!! warning
32 Before 3.8, `InitVar` is doing [type erasure](https://bugs.python.org/issue33569), which is why it's not possible for *apischema* to retrieve type information of init variables. To fix this behavior, a field metadata `init_var` can be used to put back the type of the field (`init_var` also accepts stringified type annotations).
33
34 Dataclass-like types (*attrs*/*SQLAlchemy*/etc.) can also be supported with a few lines of code, see [next section](#dataclass-like-types)
35
36 ## Standard library types
37
38 *apischema* natively handles most of the types provided by the standard library. They are sorted in the following categories:
39
40 #### Primitive
41 `str`, `int`, `float`, `bool`, `None`, subclasses of them
42
43 They correspond to JSON primitive types.
44
45 #### Collection
46
47 - `collection.abc.Collection` (*`typing.Collection`*)
48 - `collection.abc.Sequence` (*`typing.Sequence`*)
49 - `tuple` (*`typing.Tuple`*)
50 - `collection.abc.MutableSequence` (*`typing.MutableSequence`*)
51 - `list` (*`typing.List`*)
52 - `collection.abc.Set` (*`typing.AbstractSet`*)
53 - `collection.abc.MutableSet` (*`typing.MutableSet`*)
54 - `frozenset` (*`typing.FrozenSet`*)
55 - `set` (*`typing.Set`*)
56
57 They correspond to JSON *array* and are serialized to `list`.
58
59 #### Mapping
60
61 - `collection.abc.Mapping` (*`typing.Mapping`*)
62 - `collection.abc.MutableMapping` (*`typing.MutableMapping`*)
63 - `dict` (*`typing.Dict`*)
64
65 They correpond to JSON *object* and are serialized to `dict`.
66
67 #### Enumeration
68
69 `enum.Enum` subclasses, `typing.Literal`
70
71 !!! warning
72 `Enum` subclasses are (de)serialized using **values**, not names. *apischema* also provides a [conversion](conversions.md#using-enum-names) to use names instead.
73
74 #### Typing facilities
75
76 - `typing.Optional`/`typing.Union` (`Optional[T]` is strictly equivalent to `Union[T, None]`)
77
78 : Deserialization select the first matching alternative; unsupported alternatives are ignored
79
80 - `tuple` (*`typing.Tuple`*)
81
82 : Can be used as collection as well as true tuple, like `tuple[str, int]`
83
84 - `typing.NewType`
85
86 : Serialized according to its base type
87
88 - `typing.NamedTuple`
89
90 : Handled as an object type, roughly like a dataclass; fields metadata can be passed using `Annotated`
91
92 - `typing.TypedDict`
93
94 : Handled as an object type, but with a dictionary shape; fields metadata can be passed using `Annotated`
95
96 - `typing.Any`
97
98 : Untouched by deserialization, serialized according to the object runtime class
99
100 - `typing.LiteralString`
101
102 : Handled as `str`
103
104 #### Other standard library types
105
106 - `bytes`
107
108 : with `str` (de)serialization using base64 encoding
109
110 - `datetime.datetime`
111 - `datetime.date`
112 - `datetime.time`
113
114 : Supported only in 3.7+ with `fromisoformat`/`isoformat`
115
116 - `Decimal`
117
118 : With `float` (de)serialization
119
120 - `ipaddress.IPv4Address`
121 - `ipaddress.IPv4Interface`
122 - `ipaddress.IPv4Network`
123 - `ipaddress.IPv6Address`
124 - `ipaddress.IPv6Interface`
125 - `ipaddress.IPv6Network`
126 - `pathlib.Path`
127 - `re.Pattern` (*`typing.Pattern`*)
128 - `uuid.UUID`
129
130 : With `str` (de)serialization
131
132 ## Generic
133
134 `typing.Generic` can be used out of the box like in the following example:
135
136 ```python
137 {!generic.py!}
138 ```
139
140 !!! warning
141 Generic types don't have default *type name* (used in JSON/GraphQL schema) — should `Group[Foo]` be named `GroupFoo`/`FooGroup`/something else? — so they require by-class or default [`type_name` assignment](json_schema.md#set-reference-name).
142
143 ## Recursive types, string annotations and PEP 563
144
145 Recursive classes can be typed as they usually do, with or without [PEP 563](https://www.python.org/dev/peps/pep-0563/).
146 Here with string annotations:
147 ```python
148 {!recursive.py!}
149 ```
150 Here with PEP 563 (requires 3.7+)
151 ```python
152 {!recursive_postponned.py!}
153 ```
154 !!! warning
155 To resolve annotations, *apischema* uses `typing.get_type_hints`; this doesn't work really well when used on objects defined outside of global scope.
156
157 !!! warning "Warning (minor)"
158 Currently, PEP 585 can have surprising behavior when used outside the box, see [bpo-41370](https://bugs.python.org/issue41370)
159
160
161 ## `null` vs. `undefined`
162
163 Contrary to Javascript, Python doesn't have an `undefined` equivalent (if we consider `None` to be the equivalent of `null`). But it can be useful to distinguish (especially when thinking about HTTP `PATCH` method) between a `null` field and an `undefined`/absent field.
164
165 That's why *apischema* provides an `Undefined` constant (a single instance of `UndefinedType` class) which can be used as a default value everywhere where this distinction is needed. In fact, default values are used when field are absent, thus a default `Undefined` will *mark* the field as absent.
166
167 Dataclass/`NamedTuple` fields are ignored by serialization when `Undefined`.
168
169 ```python
170 {!undefined.py!}
171 ```
172
173 !!! note
174 `UndefinedType` must only be used inside an `Union`, as it has no sense as a standalone type. By the way, no suitable name was found to shorten `Union[T, UndefinedType]` but propositions are welcomed.
175
176 !!! note
177 `Undefined` is a falsy constant, i.e. `bool(Undefined) is False`.
178
179 ### Use `None` as if it was `Undefined`
180
181 Using `None` can be more convenient than `Undefined` as a placeholder for missing value, but `Optional` types are translated to nullable fields.
182
183 That's why *apischema* provides `none_as_undefined` metadata, allowing `None` to be handled as if it was `Undefined`: type will not be nullable and field not serialized if its value is `None`.
184
185 ```python
186 {!none_as_undefined.py!}
187 ```
188
189 ## Annotated - PEP 593
190
191 [PEP 593](https://www.python.org/dev/peps/pep-0593/) is fully supported; annotations stranger to *apischema* are simply ignored.
192
193 ## Custom types
194
195 *apischema* can support almost all of your custom types in a few lines of code, using the [conversion feature](conversions.md). However, it also provides a simple and direct way to support dataclass-like types, as presented [below](#dataclass-like-types-aka-object-types).
196
197 Otherwise, when *apischema* encounters a type that it doesn't support, `apischema.Unsupported` exception will be raised.
198
199 !!! note
200 In the rare case when a union member should be ignored by apischema, it's possible to use mark it as unsupported using `Union[Foo, Annotated[Bar, Unsupported]]`.
201
202 ### Dataclass-like types, aka object types
203
204 Internally, *apischema* handle standard object types — dataclasses, named tuple and typed dictionary — the same way by mapping them to a set of `apischema.objects.ObjectField`, which has the following definition:
205
206 ```python
207 @dataclass(frozen=True)
208 class ObjectField:
209 name: str # field's name
210 type: Any # field's type
211 required: bool = True # if the field is required
212 metadata: Mapping[str, Any] = field(default_factory=dict) # field's metadata
213 default: InitVar[Any] = ... # field's default value
214 default_factory: Optional[Callable[[], Any]] = None # field's default factory
215 kind: FieldKind = FieldKind.NORMAL # NORMAL/READ_ONLY/WRITE_ONLY
216 ```
217
218 Thus, support of dataclass-like types (*attrs*, *SQLAlchemy* traditional mappers, etc.) can be achieved by mapping the concerned class to its own list of `ObjectField`s; this is done using `apischema.objects.set_object_fields`.
219
220 ```python
221 {!set_object_fields.py!}
222 ```
223
224 Another way to set object fields is to directly modify *apischema* default behavior, using `apischema.settings.default_object_fields`.
225
226 !!! note
227 `set_object_fields`/`settings.default_object_fields` can be used to override existing fields. Current fields can be retrieved using `apischema.objects.object_fields`.
228
229 ```python
230 from collections.abc import Sequence
231 from typing import Optional
232 from apischema import settings
233 from apischema.objects import ObjectField
234
235 previous_default_object_fields = settings.default_object_field
236
237
238 def default_object_fields(cls) -> Optional[Sequence[ObjectField]]:
239 return [...] if ... else previous_default_object_fields(cls)
240
241
242 settings.default_object_fields = default_object_fields
243 ```
244
245 !!! note
246 Almost every default behavior of apischema can be customized using `apischema.settings`.
247
248 Examples of [*SQLAlchemy* support](examples/sqlalchemy_support.md) and [attrs support](examples/attrs_support.md) illustrate both methods (which could also be combined).
249
250 ## Skip field
251
252 Dataclass fields can be excluded from *apischema* processing by using `apischema.metadata.skip` in the field metadata. It can be parametrized with `deserialization`/`serialization` boolean parameters to skip a field only for the given operations.
253
254 ```python
255 {!skip.py!}
256 ```
257
258 !!! note
259 Fields skipped in deserialization should have a default value if deserialized, because deserialization of the class could raise otherwise.
260
261 ### Skip field serialization depending on condition
262
263 Field can also be skipped when serializing, depending on the condition given by `serialization_if`, or when the field value is equal to its default value with `serialization_default=True`.
264
265 ```python
266 {!skip_if.py!}
267 ```
268
269 ## Composition over inheritance - composed dataclasses flattening
270
271 Dataclass fields which are themselves dataclass can be "flattened" into the owning one by using `flatten` metadata. Then, when the class is (de)serialized, "flattened" fields will be (de)serialized at the same level as the owning class.
272
273 ```python
274 {!flattened.py!}
275 ```
276
277 !!! note
278 Generated JSON schema use [`unevaluatedProperties` keyword](https://json-schema.org/understanding-json-schema/reference/object.html?highlight=unevaluated#unevaluated-properties).
279
280 This feature is very convenient for building model by composing smaller components. If some kind of reuse could also be achieved with inheritance, it can be less practical when it comes to use it in code, because there is no easy way to build an inherited class when you have an instance of the super class; you have to copy all the fields by hand. On the other hand, using composition (of flattened fields), it's easy to instantiate the class when the smaller component is just a field of it.
281
282 ## FAQ
283
284 #### Why isn't `Iterable` handled with other collection types?
285 Iterable could be handled (actually, it was at the beginning), however, this doesn't really make sense from a data point of view. Iterables are computation objects, they can be infinite, etc. They don't correspond to a serialized data; `Collection` is way more appropriate in this context.
286
287 #### What happens if I override dataclass `__init__`?
288 *apischema* always assumes that dataclass `__init__` can be called with all its fields as kwargs parameters. If that's no longer the case after a modification of `__init__` (what means if an exception is thrown when the constructor is called because of bad parameters), *apischema* treats then the class as [not supported](#unsupported-types).