typelib 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
typelib/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """The top-level API for typelib.
2
+
3
+ Examples: Typical Usage
4
+ >>> import dataclasses
5
+ >>> import typelib
6
+ >>>
7
+ >>> @dataclasses.dataclass
8
+ ... class Data:
9
+ ... attr: int
10
+ ... key: str
11
+ ...
12
+ >>>
13
+ >>> typelib.unmarshal(Data, '{"key":"string","attr":"1"}')
14
+ Data(attr=1, key='string')
15
+ >>> typelib.marshal(Data(attr=1, key='string'))
16
+ {'attr': 1, 'key': 'string'}
17
+ >>> codec = typelib.codec(Data)
18
+ >>> codec.encode(Data(attr=1, key='string'))
19
+ b'{"attr":1,"key":"string"}'
20
+ >>> codec.decode(b'{"key":"string","attr":1}')
21
+ Data(attr=1, key='string')
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import importlib.metadata
27
+
28
+ from typelib.api import *
29
+
30
+ __metadata__ = importlib.metadata.metadata("typelib")
31
+ __version__ = __metadata__.get("version")
32
+ __authors__ = __metadata__.get("authors")
33
+ __license__ = __metadata__.get("license")
typelib/api.py ADDED
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ import typing as t
4
+
5
+ from typelib.codecs import Codec, DecoderT, EncoderT, codec
6
+ from typelib.marshals import AbstractMarshaller, marshal, marshaller
7
+ from typelib.py import compat, refs
8
+ from typelib.unmarshals import AbstractUnmarshaller, unmarshal, unmarshaller
9
+
10
+ __all__ = (
11
+ "AbstractMarshaller",
12
+ "AbstractUnmarshaller",
13
+ "Codec",
14
+ "decode",
15
+ "encode",
16
+ "marshal",
17
+ "marshaller",
18
+ "unmarshal",
19
+ "unmarshaller",
20
+ "compat",
21
+ "refs",
22
+ "codec",
23
+ )
24
+
25
+
26
+ T = t.TypeVar("T")
27
+
28
+
29
+ def encode(
30
+ value: T,
31
+ *,
32
+ t: type[T] | refs.ForwardRef | str | None = None,
33
+ encoder: EncoderT = compat.json.dumps,
34
+ ) -> bytes:
35
+ """Encode a value into a bytes object.
36
+
37
+ Args:
38
+ value: The value to encode.
39
+ t: A type hint for resolving the marshaller.
40
+ encoder: A callable that takes a value and returns a bytes object.
41
+ """
42
+ marshalled = marshal(value=value, t=t)
43
+ encoded = encoder(marshalled)
44
+ return encoded
45
+
46
+
47
+ def decode(
48
+ t: type[T] | refs.ForwardRef | str,
49
+ value: bytes,
50
+ *,
51
+ decoder: DecoderT = compat.json.loads,
52
+ ) -> T:
53
+ """Decode a bytes object into an instance of `t`.
54
+
55
+ Args:
56
+ t: A type hint for resolving the unmarshaller.
57
+ value: The value to decode.
58
+ decoder: A callable that takes a bytes object and returns a Python value.
59
+ """
60
+ decoded = decoder(value)
61
+ unmarshalled = unmarshal(t=t, value=decoded)
62
+ return unmarshalled