Selfie
Loading...
Searching...
No Matches
Roundtrip.py
Go to the documentation of this file.
1
from
typing
import
Any, Generic, TypeVar
2
3
# Define generic type variables
4
T = TypeVar(
"T"
)
5
SerializedForm = TypeVar(
"SerializedForm"
)
6
7
8
class
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()
selfie_lib.Roundtrip.Roundtrip
Definition
Roundtrip.py:8
selfie_lib.Roundtrip.Roundtrip.json
"Roundtrip[T, str]" json(cls)
Definition
Roundtrip.py:31
selfie_lib.Roundtrip.Roundtrip.serialize
SerializedForm serialize(self, T value)
Definition
Roundtrip.py:9
selfie_lib.Roundtrip.Roundtrip.parse
T parse(self, SerializedForm serialized)
Definition
Roundtrip.py:13
selfie_lib.Roundtrip.Roundtrip.identity
"Roundtrip[T, T]" identity(cls)
Definition
Roundtrip.py:18
selfie-lib
selfie_lib
Roundtrip.py
Generated by
1.9.8