/
toml.py
63 lines (50 loc) · 1.41 KB
/
toml.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from datetime import date, datetime, time
from typing import Any, Callable, Dict, Type, TypeVar, final
import tomli_w
from mashumaro.dialect import Dialect
from mashumaro.helper import pass_through
from mashumaro.mixins.dict import DataClassDictMixin
try:
import tomllib
except ModuleNotFoundError:
import tomli as tomllib # type: ignore
T = TypeVar("T", bound="DataClassTOMLMixin")
EncodedData = str
Encoder = Callable[[Any], EncodedData]
Decoder = Callable[[EncodedData], Dict[Any, Any]]
class TOMLDialect(Dialect):
no_copy_collections = (list, dict)
omit_none = True
serialization_strategy = {
datetime: pass_through,
date: pass_through,
time: pass_through,
}
class DataClassTOMLMixin(DataClassDictMixin):
__slots__ = ()
__mashumaro_builder_params = {
"packer": {
"format_name": "toml",
"dialect": TOMLDialect,
"encoder": tomli_w.dumps,
},
"unpacker": {
"format_name": "toml",
"dialect": TOMLDialect,
"decoder": tomllib.loads,
},
}
@final
def to_toml(
self: T,
encoder: Encoder = tomli_w.dumps,
**to_dict_kwargs: Any,
) -> EncodedData: ...
@classmethod
@final
def from_toml(
cls: Type[T],
data: EncodedData,
decoder: Decoder = tomllib.loads,
**from_dict_kwargs: Any,
) -> T: ...