File: serialized.py

package info (click to toggle)
python-apischema 0.18.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,608 kB
  • sloc: python: 15,266; sh: 7; makefile: 7
file content (44 lines) | stat: -rw-r--r-- 1,117 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
from dataclasses import dataclass

from apischema import serialize, serialized
from apischema.json_schema import serialization_schema


@dataclass
class Foo:
    @serialized
    @property
    def bar(self) -> int:
        return 0

    # Serialized method can have default argument
    @serialized
    def baz(self, some_arg_with_default: int = 1) -> int:
        return some_arg_with_default

    @serialized("aliased")
    @property
    def with_alias(self) -> int:
        return 2


# Serialized method can also be defined outside class,
# but first parameter must be annotated
@serialized
def function(foo: Foo) -> int:
    return 3


assert serialize(Foo, Foo()) == {"bar": 0, "baz": 1, "aliased": 2, "function": 3}
assert serialization_schema(Foo) == {
    "$schema": "http://json-schema.org/draft/2020-12/schema#",
    "type": "object",
    "properties": {
        "aliased": {"type": "integer"},
        "bar": {"type": "integer"},
        "baz": {"type": "integer"},
        "function": {"type": "integer"},
    },
    "required": ["bar", "baz", "aliased", "function"],
    "additionalProperties": False,
}