d42-refine 0.1.0a2__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.
d42_refine/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ from pathlib import Path
2
+
3
+ from ._errors import RefinementError, make_refinement_error
4
+ from ._operator import disable_schema_substitution, enable_schema_substitution, is_enabled
5
+ from ._refiner import Refiner, is_refinement, refine
6
+
7
+ __all__ = (
8
+ "Refiner",
9
+ "RefinementError",
10
+ "disable_schema_substitution",
11
+ "enable_schema_substitution",
12
+ "is_enabled",
13
+ "is_refinement",
14
+ "make_refinement_error",
15
+ "refine",
16
+ )
17
+ __version__ = Path(__file__).with_name("version").read_text(encoding="utf-8").strip()
d42_refine/_errors.py ADDED
@@ -0,0 +1,19 @@
1
+ from typing import Any
2
+
3
+ from th import PathHolder
4
+
5
+ __all__ = ("RefinementError", "format_path", "make_refinement_error",)
6
+
7
+
8
+ class RefinementError(Exception):
9
+ """Raised when one schema can not be refined with another schema."""
10
+
11
+
12
+ def format_path(path: PathHolder) -> str:
13
+ if len(path) == 0:
14
+ return "$"
15
+ return "$" + "".join(str(operator) for operator in path)
16
+
17
+
18
+ def make_refinement_error(path: PathHolder, message: Any) -> RefinementError:
19
+ return RefinementError(f"{format_path(path)}: {message}")
@@ -0,0 +1,45 @@
1
+ from typing import Any, Callable, Optional
2
+
3
+ from d42.declaration.types import Schema
4
+
5
+ from ._refiner import refine
6
+
7
+ __all__ = ("disable_schema_substitution", "enable_schema_substitution", "is_enabled",)
8
+
9
+ _original_mod: Optional[Callable[..., Any]] = None
10
+
11
+
12
+ def is_enabled() -> bool:
13
+ """Return ``True`` when the schema-aware ``%`` operator is enabled."""
14
+ return _original_mod is not None
15
+
16
+
17
+ def enable_schema_substitution() -> None:
18
+ """Enable ``schema % schema`` as schema refinement.
19
+
20
+ ``schema % value`` keeps the original d42 data substitution behaviour.
21
+ The function is idempotent.
22
+ """
23
+ global _original_mod
24
+ if _original_mod is not None:
25
+ return
26
+
27
+ original_mod = Schema.__mod__
28
+
29
+ def __mod__(self: Schema[Any], other: Any) -> Any:
30
+ if isinstance(other, Schema):
31
+ return refine(self, other)
32
+ return original_mod(self, other)
33
+
34
+ Schema.__override__("__mod__", __mod__)
35
+ _original_mod = original_mod
36
+
37
+
38
+ def disable_schema_substitution() -> None:
39
+ """Restore the original d42 ``%`` operator. Idempotent."""
40
+ global _original_mod
41
+ if _original_mod is None:
42
+ return
43
+
44
+ Schema.__override__("__mod__", _original_mod)
45
+ _original_mod = None