Selfie
Loading...
Searching...
No Matches
Roundtrip.py
Go to the documentation of this file.
1from typing import Any, Generic, TypeVar
2
3# Define generic type variables
4T = TypeVar("T")
5SerializedForm = TypeVar("SerializedForm")
6
7
8class Roundtrip(Generic[T, SerializedForm]):
9 def serialize(self, value: T) -> SerializedForm:
10 """Serialize a value of type T to its SerializedForm."""
11 raise NotImplementedError
12
13 def parse(self, serialized: SerializedForm) -> T:
14 """Parse the SerializedForm back to type T."""
15 raise NotImplementedError
16
17 @classmethod
18 def identity(cls) -> "Roundtrip[T, T]":
19 """Return an identity Roundtrip that does no transformation."""
20
21 class Identity(Roundtrip[Any, Any]):
22 def serialize(self, value: Any) -> Any:
23 return value
24
25 def parse(self, serialized: Any) -> Any:
26 return serialized
27
28 return Identity()
29
30 @classmethod
31 def json(cls) -> "Roundtrip[T, str]":
32 """Return a Roundtrip that serializes to/from JSON strings."""
33 import json
34
35 class JsonRoundtrip(Roundtrip[Any, str]):
36 def serialize(self, value: Any) -> str:
37 return json.dumps(value, indent=4)
38
39 def parse(self, serialized: str) -> Any:
40 return json.loads(serialized)
41
42 return JsonRoundtrip()
"Roundtrip[T, str]" json(cls)
Definition Roundtrip.py:31
SerializedForm serialize(self, T value)
Definition Roundtrip.py:9
T parse(self, SerializedForm serialized)
Definition Roundtrip.py:13
"Roundtrip[T, T]" identity(cls)
Definition Roundtrip.py:18