turbo_broccoli.custom.pathlib
pathlib
classes
1"""[`pathlib`](https://docs.python.org/3/library/pathlib.html) classes""" 2 3from pathlib import Path 4from typing import Any, Callable, Tuple 5 6from ..context import Context 7from ..exceptions import DeserializationError, TypeNotSupported 8 9 10def _path_to_json(obj: Path, ctx: Context) -> dict: 11 return {"__type__": "pathlib.path", "__version__": 1, "path": str(obj)} 12 13 14def _json_to_path(dct: dict, ctx: Context) -> Path: 15 decoders = { 16 1: _json_to_path_v1, 17 } 18 return decoders[dct["__version__"]](dct, ctx) 19 20 21def _json_to_path_v1(dct: dict, ctx: Context) -> Path: 22 return Path(dct["path"]) 23 24 25def from_json(dct: dict, ctx: Context) -> Any: 26 decoders = { 27 "pathlib.path": _json_to_path, 28 } 29 try: 30 type_name = dct["__type__"] 31 return decoders[type_name](dct, ctx) 32 except KeyError as exc: 33 raise DeserializationError() from exc 34 35 36def to_json(obj: Any, ctx: Context) -> dict: 37 """ 38 Serializes a [`pathlib`](https://docs.python.org/3/library/pathlib.html) 39 into JSON by cases. See the README for the precise list of supported types. 40 41 The return dict has the following structure: 42 43 - [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) 44 45 ```py 46 { 47 "__type__": "pathlib.path", 48 "__version__": 1, 49 "path": <str> 50 } 51 ``` 52 53 """ 54 encoders: list[Tuple[type, Callable[[Any, Context], dict]]] = [ 55 (Path, _path_to_json), 56 ] 57 for t, f in encoders: 58 if isinstance(obj, t): 59 return f(obj, ctx) 60 raise TypeNotSupported()
37def to_json(obj: Any, ctx: Context) -> dict: 38 """ 39 Serializes a [`pathlib`](https://docs.python.org/3/library/pathlib.html) 40 into JSON by cases. See the README for the precise list of supported types. 41 42 The return dict has the following structure: 43 44 - [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) 45 46 ```py 47 { 48 "__type__": "pathlib.path", 49 "__version__": 1, 50 "path": <str> 51 } 52 ``` 53 54 """ 55 encoders: list[Tuple[type, Callable[[Any, Context], dict]]] = [ 56 (Path, _path_to_json), 57 ] 58 for t, f in encoders: 59 if isinstance(obj, t): 60 return f(obj, ctx) 61 raise TypeNotSupported()
Serializes a pathlib
into JSON by cases. See the README for the precise list of supported types.
The return dict has the following structure:
-
{ "__type__": "pathlib.path", "__version__": 1, "path": <str> }