-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialization.py
56 lines (43 loc) · 1.56 KB
/
serialization.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
"""Contains the code to serialize keyword arguments to the task."""
from __future__ import annotations
import json
import uuid
from pathlib import Path
from typing import Any
from typing import Callable
from pytask import PTask
from pytask import PTaskWithPath
__all__ = ["SERIALIZERS", "create_path_to_serialized", "serialize_keyword_arguments"]
_HIDDEN_FOLDER = ".pytask/pytask-julia"
SERIALIZERS = {
"json": {"serializer": json.dumps, "suffix": ".json"},
}
try:
import yaml
except ImportError: # pragma: no cover
pass
else:
SERIALIZERS["yaml"] = {"serializer": yaml.dump, "suffix": ".yaml"}
SERIALIZERS["yml"] = {"serializer": yaml.dump, "suffix": ".yml"}
def create_path_to_serialized(task: PTask, suffix: str) -> Path:
"""Create path to serialized."""
return (
(task.path.parent if isinstance(task, PTaskWithPath) else Path.cwd())
.joinpath(_HIDDEN_FOLDER, str(uuid.uuid4()))
.with_suffix(suffix)
)
def serialize_keyword_arguments(
serializer: str | Callable[..., str] | None,
path_to_serialized: Path,
kwargs: dict[str, Any],
) -> None:
"""Serialize keyword arguments."""
if callable(serializer):
serializer_func = serializer
elif isinstance(serializer, str) and serializer in SERIALIZERS:
serializer_func = SERIALIZERS[serializer]["serializer"] # type: ignore[assignment]
else: # pragma: no cover
msg = f"Serializer {serializer!r} is not known."
raise ValueError(msg)
serialized = serializer_func(kwargs)
path_to_serialized.write_text(serialized)