From f5171fa18a87e7b49ffa888b0fca244893b0ac19 Mon Sep 17 00:00:00 2001 From: yukinarit Date: Thu, 24 Nov 2022 21:02:54 +0900 Subject: [PATCH] test: Add InitVar and ClassVar examples --- examples/class_var.py | 27 +++++++++++++++++++++++++++ examples/init_var.py | 25 +++++++++++++++++++++++++ examples/runner.py | 4 ++++ 3 files changed, 56 insertions(+) create mode 100644 examples/class_var.py create mode 100644 examples/init_var.py diff --git a/examples/class_var.py b/examples/class_var.py new file mode 100644 index 00000000..1cc921de --- /dev/null +++ b/examples/class_var.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass +from typing import ClassVar, Optional + +from serde import serde +from serde.json import from_json, to_json + + +@serde +@dataclass +class Foo: + i: int + j: Optional[int] = None + k: ClassVar[int] = 100 + + +def main(): + f = Foo(i=10, j=20) + print(f"Into Json: {to_json(f)}") + + s = '{"i": 10, "j": 20}' + print(f"From Json: {from_json(Foo, s)}") + + print(f"Class variable: Foo.k={f.k}") + + +if __name__ == '__main__': + main() diff --git a/examples/init_var.py b/examples/init_var.py new file mode 100644 index 00000000..2062d068 --- /dev/null +++ b/examples/init_var.py @@ -0,0 +1,25 @@ +from dataclasses import InitVar, dataclass +from typing import Optional + +from serde import serde +from serde.json import from_json, to_json + + +@serde +@dataclass +class Foo: + i: int + j: Optional[int] = None + k: InitVar[Optional[int]] = None + + +def main(): + f = Foo(i=10, j=20) + print(f"Into Json: {to_json(f)}") + + s = '{"i": 10, "j": 20}' + print(f"From Json: {from_json(Foo, s)}") + + +if __name__ == '__main__': + main() diff --git a/examples/runner.py b/examples/runner.py index 1a8089ce..39b39fc9 100644 --- a/examples/runner.py +++ b/examples/runner.py @@ -1,6 +1,7 @@ import sys import any +import class_var import collection import custom_class_serializer import custom_field_serializer @@ -11,6 +12,7 @@ import forward_reference import generics import generics_nested +import init_var import jsonfile import lazy_type_evaluation import literal @@ -63,6 +65,8 @@ def run_all(): run(user_exception) run(pep681) run(ellipsis) + run(init_var) + run(class_var) if PY310: import union_operator