simplibs-rules 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.
Files changed (151) hide show
  1. simplibs/rules/__init__.py +943 -0
  2. simplibs/rules/base_class/Rule.py +322 -0
  3. simplibs/rules/base_class/_NotARule.py +33 -0
  4. simplibs/rules/base_class/__init__.py +17 -0
  5. simplibs/rules/containers/AllOf.py +147 -0
  6. simplibs/rules/containers/AnyOf.py +146 -0
  7. simplibs/rules/containers/Compose.py +146 -0
  8. simplibs/rules/containers/ForEach.py +120 -0
  9. simplibs/rules/containers/NoneOf.py +112 -0
  10. simplibs/rules/containers/Not.py +97 -0
  11. simplibs/rules/containers/__init__.py +28 -0
  12. simplibs/rules/containers/_helpers/__init__.py +22 -0
  13. simplibs/rules/containers/_helpers/as_predicate.py +84 -0
  14. simplibs/rules/containers/_helpers/build_child_exception.py +39 -0
  15. simplibs/rules/containers/_helpers/describe_rule.py +72 -0
  16. simplibs/rules/containers/_helpers/validations/__init__.py +1 -0
  17. simplibs/rules/containers/_helpers/validations/raise_invalid_predicate.py +22 -0
  18. simplibs/rules/containers/_init_validators/__init__.py +23 -0
  19. simplibs/rules/containers/_init_validators/raise_container_param_not_type_error.py +52 -0
  20. simplibs/rules/containers/_init_validators/raise_requires_at_least_one_rule_error.py +37 -0
  21. simplibs/rules/containers/_init_validators/raise_rule_param_not_callable.py +54 -0
  22. simplibs/rules/containers/_init_validators/validate_compose_param_is_callable.py +72 -0
  23. simplibs/rules/predicates/__init__.py +103 -0
  24. simplibs/rules/predicates/_helpers/__init__.py +18 -0
  25. simplibs/rules/predicates/_helpers/accepts_one_positional_argument.py +127 -0
  26. simplibs/rules/predicates/_helpers/format_container.py +50 -0
  27. simplibs/rules/predicates/_init_validators/__init__.py +40 -0
  28. simplibs/rules/predicates/_init_validators/rule_errors/__init__.py +21 -0
  29. simplibs/rules/predicates/_init_validators/rule_errors/raise_has_length_param_conflict_error.py +53 -0
  30. simplibs/rules/predicates/_init_validators/rule_errors/raise_regex_param_invalid_pattern_error.py +43 -0
  31. simplibs/rules/predicates/_init_validators/rule_errors/raise_user_rule_param_wrong_arity.py +53 -0
  32. simplibs/rules/predicates/_init_validators/shared_errors/__init__.py +32 -0
  33. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_min_max_bounds_inverted_error.py +78 -0
  34. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_min_max_incomparable_error.py +65 -0
  35. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_missing_error.py +77 -0
  36. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_not_callable_error.py +51 -0
  37. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_not_container_error.py +75 -0
  38. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_not_non_negative_integer_error.py +88 -0
  39. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_not_string_error.py +77 -0
  40. simplibs/rules/predicates/_init_validators/shared_errors/raise_param_not_type_error.py +65 -0
  41. simplibs/rules/predicates/_init_validators/shared_validators/__init__.py +24 -0
  42. simplibs/rules/predicates/_init_validators/shared_validators/validate_param_is_integer.py +73 -0
  43. simplibs/rules/predicates/_init_validators/shared_validators/validate_param_is_not_zero.py +69 -0
  44. simplibs/rules/predicates/_init_validators/shared_validators/validate_param_is_primitive_number.py +76 -0
  45. simplibs/rules/predicates/_init_validators/shared_validators/validate_param_remainder_in_range.py +58 -0
  46. simplibs/rules/predicates/arithmetic/CloseTo.py +149 -0
  47. simplibs/rules/predicates/arithmetic/DivisibleBy.py +120 -0
  48. simplibs/rules/predicates/arithmetic/HasRemainder.py +137 -0
  49. simplibs/rules/predicates/arithmetic/__init__.py +21 -0
  50. simplibs/rules/predicates/checkers/IsEmpty.py +101 -0
  51. simplibs/rules/predicates/checkers/IsFalse.py +81 -0
  52. simplibs/rules/predicates/checkers/IsNone.py +81 -0
  53. simplibs/rules/predicates/checkers/IsTrue.py +80 -0
  54. simplibs/rules/predicates/checkers/NotEmpty.py +100 -0
  55. simplibs/rules/predicates/checkers/__init__.py +25 -0
  56. simplibs/rules/predicates/collections/AllUnique.py +124 -0
  57. simplibs/rules/predicates/collections/HasItem.py +131 -0
  58. simplibs/rules/predicates/collections/HasKey.py +104 -0
  59. simplibs/rules/predicates/collections/HasKeys.py +115 -0
  60. simplibs/rules/predicates/collections/IsContainer.py +99 -0
  61. simplibs/rules/predicates/collections/IsSubsetOf.py +139 -0
  62. simplibs/rules/predicates/collections/IsSupersetOf.py +138 -0
  63. simplibs/rules/predicates/collections/__init__.py +29 -0
  64. simplibs/rules/predicates/comparisons/Equals.py +87 -0
  65. simplibs/rules/predicates/comparisons/GreaterOrEqual.py +106 -0
  66. simplibs/rules/predicates/comparisons/GreaterThan.py +106 -0
  67. simplibs/rules/predicates/comparisons/InRange.py +166 -0
  68. simplibs/rules/predicates/comparisons/LessOrEqual.py +106 -0
  69. simplibs/rules/predicates/comparisons/LessThan.py +106 -0
  70. simplibs/rules/predicates/comparisons/NotEquals.py +88 -0
  71. simplibs/rules/predicates/comparisons/__init__.py +29 -0
  72. simplibs/rules/predicates/introspection/HasAttribute.py +95 -0
  73. simplibs/rules/predicates/introspection/HasLength.py +177 -0
  74. simplibs/rules/predicates/introspection/IsCallable.py +81 -0
  75. simplibs/rules/predicates/introspection/IsDataclass.py +84 -0
  76. simplibs/rules/predicates/introspection/IsHashable.py +91 -0
  77. simplibs/rules/predicates/introspection/IsInstance.py +105 -0
  78. simplibs/rules/predicates/introspection/IsIterable.py +90 -0
  79. simplibs/rules/predicates/introspection/IsSubclass.py +122 -0
  80. simplibs/rules/predicates/introspection/IsType.py +82 -0
  81. simplibs/rules/predicates/introspection/__init__.py +34 -0
  82. simplibs/rules/predicates/logic/Is.py +88 -0
  83. simplibs/rules/predicates/logic/IsIn.py +144 -0
  84. simplibs/rules/predicates/logic/IsNot.py +89 -0
  85. simplibs/rules/predicates/logic/NotIn.py +145 -0
  86. simplibs/rules/predicates/logic/UserRule.py +118 -0
  87. simplibs/rules/predicates/logic/__init__.py +24 -0
  88. simplibs/rules/predicates/numeric/IsBool.py +96 -0
  89. simplibs/rules/predicates/numeric/IsDecimal.py +83 -0
  90. simplibs/rules/predicates/numeric/IsEven.py +107 -0
  91. simplibs/rules/predicates/numeric/IsFinite.py +104 -0
  92. simplibs/rules/predicates/numeric/IsFloat.py +75 -0
  93. simplibs/rules/predicates/numeric/IsInfinity.py +97 -0
  94. simplibs/rules/predicates/numeric/IsInteger.py +118 -0
  95. simplibs/rules/predicates/numeric/IsNan.py +98 -0
  96. simplibs/rules/predicates/numeric/IsNumber.py +96 -0
  97. simplibs/rules/predicates/numeric/IsOdd.py +94 -0
  98. simplibs/rules/predicates/numeric/IsPi.py +138 -0
  99. simplibs/rules/predicates/numeric/IsPrimitiveNumber.py +87 -0
  100. simplibs/rules/predicates/numeric/IsZero.py +109 -0
  101. simplibs/rules/predicates/numeric/__init__.py +42 -0
  102. simplibs/rules/predicates/strings/Contains.py +114 -0
  103. simplibs/rules/predicates/strings/EndsWith.py +114 -0
  104. simplibs/rules/predicates/strings/IsAlnum.py +107 -0
  105. simplibs/rules/predicates/strings/IsAlpha.py +111 -0
  106. simplibs/rules/predicates/strings/IsAscii.py +109 -0
  107. simplibs/rules/predicates/strings/IsBlank.py +98 -0
  108. simplibs/rules/predicates/strings/IsDigitString.py +115 -0
  109. simplibs/rules/predicates/strings/IsLowercase.py +111 -0
  110. simplibs/rules/predicates/strings/IsString.py +104 -0
  111. simplibs/rules/predicates/strings/IsSubstringOf.py +114 -0
  112. simplibs/rules/predicates/strings/IsTitlecase.py +130 -0
  113. simplibs/rules/predicates/strings/IsUppercase.py +96 -0
  114. simplibs/rules/predicates/strings/NotBlank.py +98 -0
  115. simplibs/rules/predicates/strings/Regex.py +126 -0
  116. simplibs/rules/predicates/strings/StartsWith.py +114 -0
  117. simplibs/rules/predicates/strings/__init__.py +44 -0
  118. simplibs/rules/predicates/typing/IsAny.py +114 -0
  119. simplibs/rules/predicates/typing/IsTyping.py +100 -0
  120. simplibs/rules/predicates/typing/__init__.py +26 -0
  121. simplibs/rules/predicates/typing/_builders/ORIGIN_TABLE.py +112 -0
  122. simplibs/rules/predicates/typing/_builders/__init__.py +35 -0
  123. simplibs/rules/predicates/typing/_builders/build_annotated_rule.py +106 -0
  124. simplibs/rules/predicates/typing/_builders/build_any_of_rule.py +73 -0
  125. simplibs/rules/predicates/typing/_builders/build_callable_rule.py +63 -0
  126. simplibs/rules/predicates/typing/_builders/build_elements_rule.py +109 -0
  127. simplibs/rules/predicates/typing/_builders/build_key_value_rule.py +65 -0
  128. simplibs/rules/predicates/typing/_builders/build_literal_rule.py +60 -0
  129. simplibs/rules/predicates/typing/_builders/build_tuple_rule.py +111 -0
  130. simplibs/rules/predicates/typing/_builders/build_type_rule.py +114 -0
  131. simplibs/rules/predicates/typing/_validations/__init__.py +16 -0
  132. simplibs/rules/predicates/typing/_validations/raise_unsupported_annotation_error.py +63 -0
  133. simplibs/rules/predicates/typing/build_typing_rule.py +131 -0
  134. simplibs/rules/predicates/typing/tools/__init__.py +20 -0
  135. simplibs/rules/predicates/typing/tools/get_supported_origins.py +42 -0
  136. simplibs/rules/predicates/typing/tools/is_supported_annotation.py +60 -0
  137. simplibs/rules/testing/__init__.py +40 -0
  138. simplibs/rules/testing/assert_rule_contract.py +198 -0
  139. simplibs/rules/testing/asserts/__init__.py +27 -0
  140. simplibs/rules/testing/asserts/assert_rule_build_exception.py +149 -0
  141. simplibs/rules/testing/asserts/assert_rule_is_valid.py +90 -0
  142. simplibs/rules/testing/asserts/assert_rule_param_error.py +77 -0
  143. simplibs/rules/testing/asserts/assert_rule_raise_invalid.py +91 -0
  144. simplibs/rules/testing/asserts/assert_rule_validate.py +107 -0
  145. simplibs/rules/tools/__init__.py +16 -0
  146. simplibs/rules/tools/raise_invalid.py +84 -0
  147. simplibs_rules-0.1.0.dist-info/METADATA +372 -0
  148. simplibs_rules-0.1.0.dist-info/RECORD +151 -0
  149. simplibs_rules-0.1.0.dist-info/WHEEL +5 -0
  150. simplibs_rules-0.1.0.dist-info/licenses/LICENSE +21 -0
  151. simplibs_rules-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,322 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Annotated, Any, Callable, overload
3
+
4
+ # Inners
5
+ from ._NotARule import _NotARule
6
+
7
+
8
+ class Rule(ABC):
9
+ """Abstract base class for all validation rules.
10
+
11
+ Every concrete rule inherits from this class and implements `is_valid` and `build_exception`.
12
+ The class also provides a unified evaluation interface via `validate`, the magic `__call__` method,
13
+ and Python typing integration via `annotated`.
14
+ """
15
+
16
+ # ----------------------------------------------------------------------
17
+ # 1) Abstract Interface (mandatory for subclasses)
18
+ # ----------------------------------------------------------------------
19
+
20
+ @abstractmethod
21
+ def is_valid(
22
+ self,
23
+ value: Any,
24
+ ) -> bool:
25
+ """Return True if the tested value satisfies the rule, otherwise False."""
26
+ raise NotImplementedError
27
+
28
+ @abstractmethod
29
+ def build_exception(
30
+ self,
31
+ value: Any,
32
+ value_name: str | None = None,
33
+ context: str | None = None,
34
+ ) -> Exception:
35
+ """Create and return an exception instance (SimpleException) describing the validation failure."""
36
+ raise NotImplementedError
37
+
38
+ # ----------------------------------------------------------------------
39
+ # 2) Public Interface & Evaluation Logic
40
+ # ----------------------------------------------------------------------
41
+
42
+ def __call__(
43
+ self,
44
+ value: Any,
45
+ ) -> bool:
46
+ """Allow using the rule instance directly as a predicate function.
47
+
48
+ Returns the boolean result of `is_valid(value)`.
49
+ """
50
+ return self.is_valid(value)
51
+
52
+ def validate(
53
+ self,
54
+ value: Any,
55
+ *,
56
+ value_name: str | None = None,
57
+ context: str | None = None,
58
+ return_bool: bool = False,
59
+ return_value: bool = False,
60
+ ) -> Any:
61
+ """Validate a value against this rule.
62
+
63
+ Based on parameter flags, returns the original value, True/False,
64
+ or raises a structured exception constructed by `build_exception`.
65
+
66
+ Args:
67
+ value: The tested value.
68
+ value_name: The name of the validated parameter/variable for diagnostic reporting.
69
+ context: Additional context describing the validation environment.
70
+ return_bool: If True, returns False on failure instead of raising an exception.
71
+ return_value: If validation passes and this is True, returns original `value` instead of `True`.
72
+
73
+ Returns:
74
+ Returns `value`, `True`, or `False` depending on parameter flags.
75
+
76
+ Raises:
77
+ Exception: If validation fails and `return_bool` is False.
78
+ """
79
+ if self.is_valid(value):
80
+ return value if return_value else True
81
+
82
+ if return_bool:
83
+ return False
84
+
85
+ raise self.build_exception(
86
+ value,
87
+ value_name=value_name,
88
+ context=context,
89
+ )
90
+
91
+ # ----------------------------------------------------------------------
92
+ # 3) Typing Integration
93
+ # ----------------------------------------------------------------------
94
+
95
+ def annotated(self, type_: type) -> Any:
96
+ """Wrap this rule as `typing.Annotated[type_, self]` for type hints.
97
+
98
+ Enables seamless integration with static type checkers (MyPy, Pyright)
99
+ and runtime annotation inspection (e.g., IsTyping or decorator engines).
100
+
101
+ Args:
102
+ type_: The target base type (e.g., int, str, float).
103
+
104
+ Returns:
105
+ An `Annotated` type hint combining the base type and this rule as metadata.
106
+ """
107
+ return Annotated[type_, self]
108
+
109
+ # ----------------------------------------------------------------------
110
+ # 4) Operator-Based Composition (|, &, ~)
111
+ # ----------------------------------------------------------------------
112
+ #
113
+ # Each binary operator defines two @overload variants:
114
+ # 1) `_NotARule` (anything carrying `__not_rule__`, e.g. `Action`) -> `Any`
115
+ # MUST come first — otherwise MyPy would structurally match `Action`
116
+ # against `Callable[[Any], bool]` in the second variant (since Action is a one-arg
117
+ # callable returning `Any`, which satisfies `bool`) and mistakenly return `Rule`
118
+ # where execution actually falls back to `other.__rand__` at runtime.
119
+ # 2) `Rule | Callable[[Any], bool]` -> `Rule` — standard, documented behavior.
120
+ # The concrete method implementation below overloads remains unchanged.
121
+
122
+ @overload
123
+ def __or__(self, other: _NotARule) -> Any: ...
124
+ @overload
125
+ def __or__(self, other: "Rule | Callable[[Any], bool]") -> "Rule": ...
126
+ def __or__(self, other: "Rule | Callable[[Any], bool]") -> "Rule":
127
+ """Combine with another rule/callable via logical OR: `rule1 | rule2`.
128
+
129
+ Equivalent to `AnyOf(self, other)`. Returns `NotImplemented` if `other`
130
+ is neither a `Rule` instance nor an accepted callable, letting Python fall
131
+ back to `other.__ror__(self)` or raise `TypeError` as usual.
132
+ """
133
+ if isinstance(other, Rule) or (
134
+ callable(other) and not hasattr(other, "__not_rule__")
135
+ ):
136
+ from ..containers.AnyOf import AnyOf
137
+
138
+ return AnyOf(self, other)
139
+ return NotImplemented
140
+
141
+ @overload
142
+ def __ror__(self, other: _NotARule) -> Any: ...
143
+ @overload
144
+ def __ror__(self, other: "Rule | Callable[[Any], bool]") -> "Rule": ...
145
+ def __ror__(self, other: "Rule | Callable[[Any], bool]") -> "Rule":
146
+ """Support `other | rule` when `other` has no (or a declining) `__or__`."""
147
+ if isinstance(other, Rule) or (
148
+ callable(other) and not hasattr(other, "__not_rule__")
149
+ ):
150
+ from ..containers.AnyOf import AnyOf
151
+
152
+ return AnyOf(other, self)
153
+ return NotImplemented
154
+
155
+ @overload
156
+ def __and__(self, other: _NotARule) -> Any: ...
157
+ @overload
158
+ def __and__(self, other: "Rule | Callable[[Any], bool]") -> "Rule": ...
159
+ def __and__(self, other: "Rule | Callable[[Any], bool]") -> "Rule":
160
+ """Combine with another rule/callable via logical AND: `rule1 & rule2`.
161
+
162
+ Equivalent to `AllOf(self, other)`. Returns `NotImplemented` if `other`
163
+ is neither a `Rule` instance nor an accepted callable, letting Python fall
164
+ back to `other.__rand__(self)` or raise `TypeError` as usual.
165
+ """
166
+ if isinstance(other, Rule) or (
167
+ callable(other) and not hasattr(other, "__not_rule__")
168
+ ):
169
+ from ..containers.AllOf import AllOf
170
+
171
+ return AllOf(self, other)
172
+ return NotImplemented
173
+
174
+ @overload
175
+ def __rand__(self, other: _NotARule) -> Any: ...
176
+ @overload
177
+ def __rand__(self, other: "Rule | Callable[[Any], bool]") -> "Rule": ...
178
+ def __rand__(self, other: "Rule | Callable[[Any], bool]") -> "Rule":
179
+ """Support `other & rule` when `other` has no (or a declining) `__and__`."""
180
+ if isinstance(other, Rule) or (
181
+ callable(other) and not hasattr(other, "__not_rule__")
182
+ ):
183
+ from ..containers.AllOf import AllOf
184
+
185
+ return AllOf(other, self)
186
+ return NotImplemented
187
+
188
+ def __invert__(self) -> "Rule":
189
+ """Negate this rule via `~rule`. Equivalent to `Not(self)`."""
190
+ from ..containers.Not import Not
191
+
192
+ return Not(self)
193
+
194
+
195
+ _DESIGN_NOTES = """
196
+ # Rule — Base Abstract Class for Validation Rules
197
+
198
+ ## Purpose
199
+ The `Rule` class serves as the fundamental pillar of the entire
200
+ `simplibs-rules` library. It defines a standardized interface for
201
+ evaluating conditions, assembling structured exceptions (`SimpleException`),
202
+ and bridging validation rules with Python's typing system.
203
+
204
+ ---
205
+
206
+ ## 1. Architectural Principles & Minimalism
207
+
208
+ ### Single Responsibility
209
+ * **Evaluation Scope:** The `Rule` class is exclusively concerned with
210
+ whether a value satisfies the condition (`is_valid`) and how the exception
211
+ card looks on failure (`build_exception`).
212
+ * **`None` Value Handling:** The rule itself does not special-case `None`.
213
+ If `None` needs to be treated as a valid value, compose it explicitly
214
+ with `IsNone` (e.g. `rule | IsNone()`) rather than relying on a global
215
+ flag.
216
+
217
+ ### Zero Import-Time Overhead
218
+ * Unnecessary metaclass inspection routines have been removed in accordance with
219
+ the **Programmer's Zen** philosophy. Documentation and usage examples are
220
+ audited via automated unit tests rather than import-time hooks.
221
+
222
+ ---
223
+
224
+ ## 2. Core Methods
225
+
226
+ ### `is_valid(value) -> bool`
227
+ * Pure abstract method.
228
+ * Must never raise exceptions for standard validation failures—always
229
+ returns strictly `True` or `False`.
230
+
231
+ ### `build_exception(value, value_name, context) -> Exception`
232
+ * Constructs and returns an exception instance (typically from the
233
+ `simplibs-exception` family).
234
+ * The exception is only **assembled and returned**, not raised directly in
235
+ this method.
236
+
237
+ ### `__call__(value) -> bool`
238
+ * Callable magic method enabling direct predicate invocation.
239
+
240
+ ### `validate(value, ...)`
241
+ * Primary evaluation method offering a flexible return interface:
242
+ 1. Value passes & `return_value=True` -> returns `value`.
243
+ 2. Value passes & `return_value=False` -> returns `True`.
244
+ 3. Value fails & `return_bool=True` -> returns `False`.
245
+ 4. Value fails & `return_bool=False` -> raises exception from
246
+ `build_exception(...)`.
247
+
248
+ ---
249
+
250
+ ## 3. Typing System Integration (`annotated`)
251
+
252
+ Bridges runtime validation rules directly into Python's standard type
253
+ annotation machinery via `typing.Annotated` (PEP 593) — see `annotated()`
254
+ docstring and `validated_type()` for the named-type equivalent.
255
+
256
+ ---
257
+
258
+ ## 4. Operator-Based Composition (`|`, `&`, `~`)
259
+
260
+ * **`rule1 | rule2`** (`__or__` / `__ror__`) -> `AnyOf(rule1, rule2)`.
261
+ * **`rule1 & rule2`** (`__and__` / `__rand__`) -> `AllOf(rule1, rule2)`.
262
+ * **`~rule`** (`__invert__`) -> `Not(rule)`.
263
+ * **Lazy Imports:** Container imports (`AnyOf`, `AllOf`, `Not`) are deferred
264
+ inside method bodies to prevent circular import issues.
265
+ * **`NotImplemented` Fallback:** Binary operators return `NotImplemented` for
266
+ unsupported types, allowing Python's standard reflected operator
267
+ protocols to execute naturally.
268
+
269
+ ---
270
+
271
+ ## 5. The `__not_rule__` Hook — Opting Out of Rule-Side Composition
272
+
273
+ `__not_rule__` is a bare class-level marker — its *presence*, not its
274
+ value, is what matters. `Rule.__and__`/`__or__`/`__rand__`/`__ror__` check
275
+ `callable(other) and not hasattr(other, "__not_rule__")` before treating
276
+ `other` as a plain predicate to fold into `AllOf`/`AnyOf`. Any callable
277
+ carrying this marker (e.g. `simplibs-actions`' `Action`) is
278
+ deliberately excluded and gets `NotImplemented` instead, handing control
279
+ back to Python's operator protocol — which then tries `other`'s own
280
+ reflected method.
281
+
282
+ Any future callable class with the same need — composable, but meant to
283
+ *consume and orchestrate* rules rather than be silently folded into
284
+ one — should carry the same `__not_rule__` marker.
285
+
286
+ ---
287
+
288
+ ## 6. Typing the `__not_rule__` Split — `_NotARule` Protocol, Not an Import
289
+
290
+ `Rule.py`'s overloads need to tell a type checker "when `other` carries
291
+ `__not_rule__`, don't assume this returns `Rule`" — but `Rule` lives in
292
+ `simplibs-rules`, a lower layer that downstream packages build on top
293
+ of. Importing higher-level abstractions here (even under `TYPE_CHECKING`)
294
+ would introduce a reverse dependency.
295
+
296
+ `_NotARule` is a structural `Protocol` (`__not_rule__: Any` + a one-arg
297
+ `__call__`) instead — it matches `Action` (and anything shaped like it)
298
+ without `Rule` ever needing to know it exists. The overload
299
+ returns `Any` for this case rather than a precise type, because `Rule`
300
+ genuinely does not know what `other.__rand__`/`__ror__` will produce.
301
+
302
+ **Overload ordering matters and is not cosmetic.** The `_NotARule`
303
+ overload is listed *first* on every operator. `@overload` resolution is
304
+ first-match, top-to-bottom — and `Action` structurally satisfies
305
+ `Callable[[Any], bool]` too (it's callable with one positional argument;
306
+ its `Any` return is compatible with an expected `bool`). Without the
307
+ `_NotARule` overload coming first, a type checker would silently match
308
+ `Action` against the generic callable overload and infer `Rule` as the
309
+ result of `rule & action` — which is wrong the moment `Rule.__and__`
310
+ actually returns `NotImplemented` and execution falls through to
311
+ `Action.__rand__` at runtime. Putting the exclusion case first prevents
312
+ that false precision.
313
+
314
+ ---
315
+
316
+ ## 7. Ecosystem Integration
317
+
318
+ * **`simplibs-exception`:** `build_exception` utilizes `value_name` as `label`,
319
+ `context`, and `value` to format readable diagnostic cards.
320
+ * **`IsTyping`:** Automatically extracts `Rule` instances attached
321
+ via `.annotated()` to decompose typing constructs into composed validation trees.
322
+ """
@@ -0,0 +1,33 @@
1
+ from typing import Any, Protocol
2
+
3
+
4
+ class _NotARule(Protocol):
5
+ """Structural stand-in for `Action` and future non-rule callable classes.
6
+
7
+ Matches any callable carrying the `__not_rule__` marker attribute without
8
+ requiring `Rule` to import or know about `Action` directly.
9
+ """
10
+
11
+ __not_rule__: Any
12
+
13
+ def __call__(self, __data: Any) -> Any: ...
14
+
15
+
16
+ _DESIGN_NOTES = """
17
+ # _NotARule — Structural Protocol for Rule Exclusion
18
+
19
+ ## Purpose
20
+ `_NotARule` is a private typing protocol used inside `Rule.py` to type-check
21
+ binary operators (`|`, `&`) when interacting with non-rule composable callables
22
+ such as `simplibs-actions`' `Action`.
23
+
24
+ ## Why a Protocol?
25
+ 1. **Layering Independence:** `simplibs-rules` is a lower-level library.
26
+ Importing higher-level entities (like `Action`) here would introduce a circular
27
+ or backward dependency.
28
+ 2. **Type-Checker Accuracy:** By placing `_NotARule` as the first `@overload`
29
+ variant in `Rule`'s operator signatures, static type checkers (MyPy, Pyright)
30
+ will correctly infer that operator expressions involving `Action` hand control
31
+ over to `Action`'s reflected operators (`__rand__`, `__ror__`) rather than
32
+ treating `Action` as a plain predicate callable and wrapping it into `AllOf`/`AnyOf`.
33
+ """
@@ -0,0 +1,17 @@
1
+ from .Rule import Rule
2
+
3
+
4
+ _DESIGN_NOTES = """
5
+ # Rule Base Class Sub-Package
6
+
7
+ ## Purpose
8
+ Holds the abstract base class that every concrete validation rule in the
9
+ library inherits from, defining the common evaluation and exception-building
10
+ contract.
11
+
12
+ ## Internal Components Registry
13
+
14
+ | Component | Type | Description |
15
+ | :-------- | :---- | :------------------------------------------------------------------------------|
16
+ | `Rule` | Class | Abstract base class defining `is_valid`, `build_exception`, `__call__`, `validate`. |
17
+ """
@@ -0,0 +1,147 @@
1
+ from typing import Any, Callable
2
+ from simplibs.exception import ValidationError
3
+ # Outers
4
+ from ..base_class import Rule
5
+ # Inners
6
+ from ._helpers import as_predicate, build_child_exception
7
+ from ._init_validators import (
8
+ raise_requires_at_least_one_rule_error,
9
+ raise_rule_param_not_callable
10
+ )
11
+
12
+
13
+ class AllOf(Rule):
14
+ """Value must satisfy every one of the given rules.
15
+
16
+ Rule:
17
+ all(rule(value) for rule in rules)
18
+
19
+ Example:
20
+ validate(value, AllOf(IsInteger(), GreaterThan(0)))
21
+ validate(value, IsInteger() & GreaterThan(0))
22
+ """
23
+
24
+ __slots__ = ("rules",)
25
+
26
+ # ----------------------------------------------------------------------
27
+ # Constructor initialization
28
+ # ----------------------------------------------------------------------
29
+ def __init__(self, *rules: Rule | Callable[[Any], bool]) -> None:
30
+
31
+ # 1. Parameter validation
32
+ if not rules:
33
+ raise_requires_at_least_one_rule_error("AllOf")
34
+
35
+ # 2. Flatten nested AllOf instances (e.g. from `a & b & c` chaining)
36
+ # into a single flat rule list, rather than nesting AllOf(AllOf(...), ...)
37
+ flattened: list[Rule | Any] = []
38
+ for rule in rules:
39
+ if not callable(rule):
40
+ raise_rule_param_not_callable("AnyOf", rule)
41
+ if type(rule) is AllOf:
42
+ flattened.extend(rule.rules)
43
+ else:
44
+ flattened.append(rule)
45
+
46
+ # 3. Parameter assignment
47
+ self.rules = tuple(flattened)
48
+
49
+ # ----------------------------------------------------------------------
50
+ # Rule definition
51
+ # ----------------------------------------------------------------------
52
+ def is_valid(self, value: Any) -> bool:
53
+
54
+ # 1. Evaluate whether the value satisfies all rules
55
+ return all(
56
+ as_predicate(rule)(value)
57
+ for rule in self.rules
58
+ )
59
+
60
+ # ----------------------------------------------------------------------
61
+ # Exception definition
62
+ # ----------------------------------------------------------------------
63
+ def build_exception(
64
+ self,
65
+ value: Any,
66
+ value_name: str | None = None,
67
+ context: str | None = None,
68
+ ) -> Exception:
69
+
70
+ # 1. Raise the exception for the first failing rule
71
+ for rule in self.rules:
72
+ if not as_predicate(rule)(value):
73
+ return build_child_exception(rule, value, value_name, context)
74
+
75
+ # 2. Fallback (build exception if all rules unexpectedly passed)
76
+ return ValidationError(
77
+ error_name="ALL_OF_UNREACHABLE_ERROR",
78
+ label=value_name,
79
+ expected="value satisfying all rules",
80
+ value=value,
81
+ problem="All rules unexpectedly passed during error construction.",
82
+ context=context,
83
+ how_to_fix=("Check validation logic state.",),
84
+ exception=RuntimeError,
85
+ )
86
+
87
+
88
+ _DESIGN_NOTES = """
89
+ # AllOf — Logical AND Container Validation Rule
90
+
91
+ ## Purpose
92
+ The `AllOf` rule aggregates multiple validation rules or callables,
93
+ requiring an input value to satisfy ALL contained rules (logical
94
+ conjunction / AND). It is also the rule constructed under the hood by
95
+ `Rule.__and__`/`Rule.__rand__` (`rule1 & rule2`).
96
+
97
+ ---
98
+
99
+ ## 1. Execution Rationale & Short-Circuit Evaluation
100
+
101
+ * **Constructor Fail-Fast:**
102
+ Requires at least one child rule during initialization via
103
+ `raise_requires_at_least_one_rule_error` (`ParamError`).
104
+ * **Short-Circuit Evaluation:**
105
+ Uses Python's native `all()` to short-circuit upon encountering the first
106
+ failing rule.
107
+ * **Child Exception Delegation:**
108
+ In `build_exception`, iterates through rules, finds the first failing
109
+ rule, and delegates exception generation to `build_child_exception`.
110
+
111
+ ---
112
+
113
+ ## 2. Self-Flattening Constructor
114
+
115
+ * **Why It's Needed:**
116
+ `Rule.__and__` builds `AllOf` instances one pair at a time, so a chained
117
+ expression like `a & b & c` evaluates left-to-right as `(a & b) & c`,
118
+ which — without flattening — would construct a nested
119
+ `AllOf(AllOf(a, b), c)` rather than a flat `AllOf(a, b, c)`.
120
+ * **Why Nesting Would Be a Problem:**
121
+ `build_exception` delegates to the *first failing sub-rule* via
122
+ `build_child_exception`. For a nested `AllOf`, that delegation would
123
+ correctly recurse into the inner `AllOf.build_exception()` and still
124
+ surface the true failing rule's card — so nesting wouldn't break
125
+ diagnostics the way it would for `AnyOf` — but it would still create
126
+ needless extra object instances and an unnecessarily deep call chain on
127
+ every evaluation. Flattening keeps `AllOf` consistent with `AnyOf` and
128
+ avoids that overhead.
129
+ * **How It Works:**
130
+ During `__init__`, every positional `rule` argument is inspected with
131
+ `type(rule) is AllOf` (exact type match, not `isinstance`, so a
132
+ deliberate `AllOf` subclass overriding behavior is never silently
133
+ unwrapped). Matching instances contribute their own `.rules` directly
134
+ instead of themselves, applied at every position in the argument list —
135
+ not just the first — so both `(a & b) & c` and `c & (a & b)` flatten to
136
+ the same `AllOf(a, b, c)`.
137
+ * **Applies Equally to Manual Construction:**
138
+ This also fixes `AllOf(AllOf(a, b), c)` written by hand, not just
139
+ operator-chained expressions.
140
+
141
+ ---
142
+
143
+ ## 3. Exception Card Design
144
+
145
+ * **Transparent Delegation:** Vends the exact child exception card of the
146
+ failing sub-rule.
147
+ """
@@ -0,0 +1,146 @@
1
+ from typing import Any, Callable
2
+ from simplibs.exception import ValidationError
3
+ # Outers
4
+ from ..base_class import Rule
5
+ # Inners
6
+ from ._helpers import as_predicate, describe_rule
7
+ from ._init_validators import (
8
+ raise_requires_at_least_one_rule_error,
9
+ raise_rule_param_not_callable
10
+ )
11
+
12
+
13
+ class AnyOf(Rule):
14
+ """Value must satisfy at least one of the given rules.
15
+
16
+ Rule:
17
+ any(rule(value) for rule in rules)
18
+
19
+ Example:
20
+ validate(value, AnyOf(IsInteger(), IsFloat()))
21
+ validate(value, IsInteger() | IsFloat())
22
+ """
23
+
24
+ __slots__ = ("rules",)
25
+
26
+ # ----------------------------------------------------------------------
27
+ # Constructor initialization
28
+ # ----------------------------------------------------------------------
29
+ def __init__(self, *rules: Rule | Callable[[Any], bool]) -> None:
30
+
31
+ # 1. Parameter validation
32
+ if not rules:
33
+ raise_requires_at_least_one_rule_error("AnyOf")
34
+
35
+ # 2. Flatten nested AnyOf instances (e.g. from `a | b | c` chaining)
36
+ # into a single flat rule list, rather than nesting AnyOf(AnyOf(...), ...)
37
+ flattened: list[Rule | Any] = []
38
+ for rule in rules:
39
+ if not callable(rule):
40
+ raise_rule_param_not_callable("AnyOf", rule)
41
+ if type(rule) is AnyOf:
42
+ flattened.extend(rule.rules)
43
+ else:
44
+ flattened.append(rule)
45
+
46
+ # 3. Parameter assignment
47
+ self.rules = tuple(flattened)
48
+
49
+ # ----------------------------------------------------------------------
50
+ # Rule definition
51
+ # ----------------------------------------------------------------------
52
+ def is_valid(self, value: Any) -> bool:
53
+
54
+ # 1. Evaluate whether the value satisfies at least one rule
55
+ return any(
56
+ as_predicate(rule)(value)
57
+ for rule in self.rules
58
+ )
59
+
60
+ # ----------------------------------------------------------------------
61
+ # Exception definition
62
+ # ----------------------------------------------------------------------
63
+ def build_exception(
64
+ self,
65
+ value: Any,
66
+ value_name: str | None = None,
67
+ context: str | None = None,
68
+ ) -> Exception:
69
+
70
+ # 1. Prepare data
71
+ descriptions = ", ".join(describe_rule(rule) for rule in self.rules)
72
+
73
+ # 2. Build the exception
74
+ return ValidationError(
75
+ error_name="ANY_OF_ERROR",
76
+ label=value_name,
77
+ expected=f"value satisfying at least one of: {descriptions}",
78
+ value=value,
79
+ problem=f"Value did not satisfy any of: {descriptions}.",
80
+ context=context,
81
+ how_to_fix=(
82
+ f"Provide a value that satisfies at least one of: {descriptions}.",
83
+ ),
84
+ exception=ValueError,
85
+ )
86
+
87
+
88
+ _DESIGN_NOTES = """
89
+ # AnyOf — Logical OR Container Validation Rule
90
+
91
+ ## Purpose
92
+ The `AnyOf` rule aggregates multiple validation rules or callables,
93
+ requiring an input value to satisfy AT LEAST ONE contained rule (logical
94
+ disjunction / OR). It is also the rule constructed under the hood by
95
+ `Rule.__or__`/`Rule.__ror__` (`rule1 | rule2`).
96
+
97
+ ---
98
+
99
+ ## 1. Execution Rationale & Short-Circuit Evaluation
100
+
101
+ * **Constructor Fail-Fast:**
102
+ Guards against empty rule sets on instantiation via
103
+ `raise_requires_at_least_one_rule_error` (`ParamError`).
104
+ * **Short-Circuit Evaluation:**
105
+ Uses Python's native `any()` to short-circuit upon encountering the first
106
+ passing rule.
107
+ * **Composite Error Aggregation:**
108
+ Since all rules fail when `build_exception` is reached, `AnyOf` aggregates
109
+ string descriptions of all sub-rules via `describe_rule`.
110
+
111
+ ---
112
+
113
+ ## 2. Self-Flattening Constructor
114
+
115
+ * **Why It's Needed:**
116
+ `Rule.__or__` builds `AnyOf` instances one pair at a time, so a chained
117
+ expression like `a | b | c` evaluates left-to-right as `(a | b) | c`,
118
+ which — without flattening — would construct a nested
119
+ `AnyOf(AnyOf(a, b), c)` rather than a flat `AnyOf(a, b, c)`.
120
+ * **Why Nesting Would Be a Problem:**
121
+ `build_exception` calls `describe_rule(rule)` for every sub-rule to list
122
+ candidate requirements. `describe_rule` on a nested `AnyOf` instance
123
+ returns only `"AnyOf"` (its class name), producing an unreadable
124
+ diagnostic like *"expected one of: AnyOf, IsFloat"* instead of
125
+ *"expected one of: IsInteger, IsFloat, IsFloat"* — a real regression in
126
+ diagnostic quality, not just cosmetic nesting.
127
+ * **How It Works:**
128
+ During `__init__`, every positional `rule` argument is inspected with
129
+ `type(rule) is AnyOf` (exact type match, not `isinstance`, so a
130
+ deliberate `AnyOf` subclass overriding behavior is never silently
131
+ unwrapped). Matching instances contribute their own `.rules` directly
132
+ instead of themselves, applied at every position in the argument list —
133
+ not just the first — so both `(a | b) | c` and `c | (a | b)` flatten to
134
+ the same `AnyOf(a, b, c)`.
135
+ * **Applies Equally to Manual Construction:**
136
+ This also fixes `AnyOf(AnyOf(a, b), c)` written by hand, not just
137
+ operator-chained expressions.
138
+
139
+ ---
140
+
141
+ ## 3. Exception Card Design
142
+
143
+ * **Error Classification:** Uses `ANY_OF_ERROR` wrapping a `ValueError`.
144
+ * **Summary Listing:** Concatenates rule descriptions to form a transparent
145
+ overview of candidate requirements.
146
+ """