📏 simplibs-rules
Composable, explicit validation rules — pure predicates, zero transformation.
A lightweight, high-performance Python library defining atomic, composable validation
rules built on a clean Rule abstraction. Rules combine naturally with plain
Python operators (|, &, ~), carry structured, human-readable diagnostics
on failure via simplibs-exception, and — through integrated type
decomposition — understand Python's typing annotations natively.
from simplibs.rules import is_integer, greater_than, IsTyping
# Operator composition
positive_int = is_integer & greater_than(0)
positive_int.is_valid(5) # -> True
positive_int.is_valid(-5) # -> False
# Type annotation decomposition
rule = IsTyping(list[int] | None)
rule.is_valid([1, 2, 3]) # -> True
rule.is_valid(["1", "2"]) # -> False
simplibs-rulesis the foundational rule engine of the ecosystem. If you just want to validate values in your own code without composing rules by hand, seesimplibs-validate, which buildsvalidate(), ready-madevalidate_*wrappers, and self-validating decorators on top of this library.
🧭 The Core Philosophy
Most validation approaches force a choice: write ad-hoc if/raise checks scattered
through your codebase, or adopt heavy data-transformation frameworks.
simplibs-rules is a pure predicate engine. A Rule never transforms or coerces
a value; it only ever answers "does this value satisfy me?" and, on failure,
provides structured, precise diagnostic exceptions.
Every rule is a small, composable object. You combine them with plain Python operators instead of writing nested configuration or custom functions:
is_string & has_length(min_length=3) & not_blank
By decoupling rule definitions and evaluation logic from validation
invocation wrappers, simplibs-rules serves as the foundational rule engine
for higher-level validation tools — such as simplibs-validate
(the validate() entry point, ready-made wrappers, self-validating decorators) and the
upcoming simplibs-types (reusable, named validated types built on Rule).
📦 Installation
pip install simplibs-rules
🚀 Quick Start in 60 Seconds
Level 1: Evaluating rules directly
from simplibs.rules import is_integer, greater_than
rule = is_integer & greater_than(0)
rule.is_valid(5) # -> True
rule.is_valid(-5) # -> False
# Raising structured exceptions
if not rule.is_valid(-5):
raise rule.build_exception(-5, value_name="age")
Level 2: Rule execution with return options
rule = is_integer & greater_than(0)
rule.validate(5) # -> True
rule.validate(5, return_value=True) # -> 5
rule.validate(-5, return_bool=True) # -> False
rule.validate(-5) # -> raises ValidationError
Level 3: Annotation-driven rules
from simplibs.rules import IsTyping, build_typing_rule
# Converts complex typing constructs directly into rule trees:
typing_rule = IsTyping(dict[str, int])
typing_rule.is_valid({"apples": 5, "oranges": 10}) # -> True
typing_rule.is_valid({"apples": "5"}) # -> False
# A failing entry is named by its key, not by its position:
typing_rule.validate({"apples": "5"}, value_name="stock") # fails at stock['apples']
Level 4: Readable descriptions
Every rule can say what it requires in a few words, and containers and annotations compose those texts — so a failure names what was expected instead of class names:
rule = IsTyping(list[int] | set[int] | str)
rule.describe() # -> "list[int] | set[int] | str"
(is_integer & greater_than(0)).describe() # -> "int & > 0"
rule.validate(["a"], value_name="payload")
# Expected: value satisfying at least one of: list[int], set[int], str
🛠️ Architecture & Package Structure
src/simplibs/rules/
├── base_class/ ◄── Abstract base class Rule & internal helpers (_NotARule)
│ ├── Rule.py
│ └── _NotARule.py
├── containers/ ◄── Rule combinators (AllOf, AnyOf, Not, NoneOf, ForEach, ForEachKey, ForEachValue, Compose, Described)
├── predicates/ ◄── Single-purpose predicate rules
│ ├── arithmetic/ ◄── CloseTo, DivisibleBy, HasRemainder
│ ├── checkers/ ◄── IsEmpty, NotEmpty, IsNone, IsTrue, IsFalse
│ ├── collections/ ◄── IsContainer, HasItem, HasKey, HasKeys, AllUnique, IsSubsetOf, IsSupersetOf
│ ├── comparisons/ ◄── Equals, NotEquals, GreaterThan, GreaterOrEqual, LessThan, LessOrEqual, InRange
│ ├── introspection/ ◄── IsInstance, IsType, IsSubclass, IsDataclass, IsCallable, IsHashable, IsIterable, IsReiterable, HasAttribute, HasLength
│ ├── logic/ ◄── Is, IsNot, IsIn, NotIn, UserRule
│ ├── numeric/ ◄── IsBool, IsInteger, IsFloat, IsDecimal, IsNumber, IsPrimitiveNumber, IsZero, IsNan, IsInfinity, IsPi, IsEven, IsOdd, IsFinite
│ ├── strings/ ◄── IsString, Contains, IsSubstringOf, StartsWith, EndsWith, Regex, IsBlank, NotBlank, IsAlnum, IsAlpha, IsAscii, IsDigitString, IsLowercase, IsTitlecase, IsUppercase, IsIdentifier, IsPrintable, IsWhitespace
│ └── typing/ ◄── Annotation-driven evaluation (IsAny, IsTyping, build_typing_rule)
└── testing/ ◄── Testing contracts for Rule implementations
└── assert_rule_contract.py
🧩 The Rule Class
Every rule in this library inherits from Rule. It defines the mandatory
contract (is_valid, build_exception) and provides full composition
capabilities out of the box.
class Rule(ABC):
__slots__ = ()
@abstractmethod
def is_valid(self, value: Any) -> bool:
"""Return True if the tested value satisfies the rule, otherwise False."""
raise NotImplementedError
@abstractmethod
def build_exception(
self,
value: Any,
value_name: str | None = None,
context: str | None = None,
) -> Exception:
"""Create and return a structured exception describing the validation failure."""
raise NotImplementedError
def __call__(self, value: Any) -> bool:
"""Allow using the rule instance directly as a predicate function."""
return self.is_valid(value)
def validate(
self,
value: Any,
*,
value_name: str | None = None,
context: str | None = None,
return_bool: bool = False,
return_value: bool = False,
) -> Any:
"""Validate a value against this rule."""
if self.is_valid(value):
return value if return_value else True
if return_bool:
return False
raise self.build_exception(value, value_name=value_name, context=context)
def describe(self) -> str:
"""Return a short, human-readable description of what this rule requires."""
return type(self).__name__
def annotated(self, type_: type) -> Any:
"""Wrap this rule as `typing.Annotated[type_, self]` for type hints."""
return Annotated[type_, self]
# Operators for logical composition with @overload support for non-rule callables
@overload
def __or__(self, other: _NotARule) -> Any: ...
@overload
def __or__(self, other: Rule | Callable[[Any], bool]) -> Rule: ...
@overload
def __and__(self, other: _NotARule) -> Any: ...
@overload
def __and__(self, other: Rule | Callable[[Any], bool]) -> Rule: ...
def __invert__(self) -> Rule: ...
➡️ Full method-by-method reference: README_RULE_CLASS
📖 Rule Quick Reference
Every built-in Rule is exposed in two ways: as its class (IsInteger),
and as a snake_case shortcut (is_integer) — a pre-instantiated object
for zero-parameter rules, or the class itself for parameterized ones.
Both are fully interchangeable.
containers/ — Composing other rules
| Class | Shortcut | Description / Parameters |
|---|---|---|
AllOf |
all_of |
Logical AND across multiple rules (*rules). Behind &. |
AnyOf |
any_of |
Logical OR across multiple rules (*rules). Behind |. |
Compose |
compose |
Transforms value before checking (transformer, validator). |
ForEach |
for_each |
Validates every item in an iterable (rule). |
ForEachKey |
for_each_key |
Validates every key of a mapping (rule). |
ForEachValue |
for_each_value |
Validates every value of a mapping; a failing one is named by its key (rule). |
NoneOf |
none_of |
Value must satisfy none of the given rules (*rules). |
Not |
negate |
Logical NOT for a single rule (rule). Behind ~. |
Described |
- | Behaves like the wrapped rule, but describes itself with a fixed text (rule, text). |
predicates/ — Atomic predicates
-
arithmetic/:CloseTo,DivisibleBy,HasRemainder
README_RULE_PREDICATE_ARITHMETIC -
checkers/:IsEmpty,NotEmpty,IsNone,IsTrue,IsFalse
README_RULE_PREDICATE_CHECKERS -
collections/:IsContainer,HasItem,HasKey,HasKeys,AllUnique,IsSubsetOf,IsSupersetOf
README_RULE_PREDICATE_COLLECTIONS -
comparisons/:Equals,NotEquals,GreaterThan,GreaterOrEqual,LessThan,LessOrEqual,InRange
README_RULE_PREDICATE_COMPARISONS -
introspection/:IsInstance,IsType,IsSubclass,IsDataclass,IsCallable,IsHashable,IsIterable,IsReiterable,HasAttribute,HasLength
README_RULE_PREDICATE_INTROSPECTION -
logic/:Is,IsNot,IsIn,NotIn,UserRule
README_RULE_PREDICATE_LOGIC -
numeric/:IsBool,IsInteger,IsFloat,IsDecimal,IsNumber,IsPrimitiveNumber,IsZero,IsNan,IsInfinity,IsPi,IsEven,IsOdd,IsFinite
README_RULE_PREDICATE_NUMERIC -
strings/:IsString,Contains,IsSubstringOf,StartsWith,EndsWith,Regex,IsBlank,NotBlank,IsAlnum,IsAlpha,IsAscii,IsDigitString,IsLowercase,IsTitlecase,IsUppercase,IsIdentifier,IsPrintable,IsWhitespace
README_RULE_PREDICATE_STRINGS
predicates/typing/ — Annotation-driven evaluation
| Class / Function | Shortcut | Description |
|---|---|---|
IsAny |
is_any |
Always passes (True). Represents typing.Any. |
IsTyping |
is_typing |
Recursively converts an annotation into a Rule tree. |
build_typing_rule |
- | Functional entry point for annotation decomposition. |
IsTyping recursively decomposes an arbitrary type annotation (list[int], dict[str,
int] | None, Literal[...], Callable[...], ...) into a composed Rule tree — the
mechanism that also powers simplibs-validate's validate_call/validate_dataclass.
One-shot iterators:
Iterable[T]checks the value item by item, which would consume a generator, so a generator (or any other one-shot iterator) is rejected with a clear error instead of being passed on exhausted — seeIsReiterable. PlainIterablestill accepts generators; use alist/tuple/set(orCollection[T]) to have items checked.
➡️ README_RULE_TYPING — the public IsTyping/build_typing_rule entry points
➡️ README_RULE_TYPING_BUILDERS — the internal per-construct decomposition engine
🧪 Testing Utilities
simplibs-rules includes its own contract testing tools to ensure custom or existing Rule
implementations strictly follow all rules and return modes:
assert_rule_contract: Verifies is_valid, direct calling, the validate() matrix and return
modes, exception generation consistency, the describe() text contract and __slots__
integrity — plus, optionally, the constructor's ParamError guard — for any Rule instance.
➡️ README_TESTING_ASSERTS_RULE_CONTRACT
⚠️ Exceptions
Diagnostic exceptions built by build_exception() are structured
simplibs.exception.SimpleException cards
rather than bare tracebacks. simplibs-validate builds its own ValidateError hierarchy
on top of the same mechanism for the higher-level entry points (validate(),
validate_call, ...).
🔗 Related libraries
simplibs-validate— thevalidate()entry point, ready-made validate_* wrappers, operational tools (raise_invalid, validated_type), and self-validating decorators (validate_call, validate_dataclass) built on top of Rule.simplibs-types— reusable, named validated types (Annotated[type, Rule]combinations) built onRule, for sharing a single constraint definition across many annotations.
☯️ About simplibs
All libraries in the simplibs (Simple Libraries) ecosystem share a common engineering philosophy:
- Dyslexia-friendly: We actively minimize cognitive load. Code is atomized into small, self-contained units, files are named directly after the logical task they perform, and explanations describe why something is designed, not just what it is.
- Programmer's Zen: Nothing should be missing, and nothing should be superfluous. We value clean execution paths and robust, understandable code architectures over rushed, messy feature sets.
- Defensive Style: We actively anticipate edge cases and failure modes so that only safe operational paths remain. Our code is built to degrade gracefully rather than crash unexpectedly.
- Minimalism: Find the most direct path to the goal in as few operational steps as possible without taking shortcuts on safety, readability, or completeness.
- Code as Craft: Code should be pleasant to look at, readable at a glance, and evoke structural harmony. We treat software engineering as a precision trade.
🤝 Contributing & Community
This is an open-source project built with love and care. We strongly believe in community collaboration and welcome any feedback, bug reports, or feature ideas!
- Want to contribute? Feel free to open an Issue or submit a Pull Request.
- Want to get in touch? If you'd like to discuss the project further, collaborate, or just say hello, feel free to open a GitHub Issue or start a Discussion.
📝 License
This library is released under the MIT License. Build great things!
Metadata
Release files for simplibs-rules 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| simplibs_rules-0.5.0.tar.gz | 138.9 kB | Without provenance | Details for simplibs_rules-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| simplibs_rules-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for simplibs_rules-0.5.0-py3-none-any.whl |
Total release size: 393.1 kB
Release files / simplibs_rules-0.5.0.tar.gz
| Download URL | simplibs_rules-0.5.0.tar.gz |
|---|---|
| Size | 138.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9f5376454019b49b1c048af64a55795a8226af3a735ad5bcd0610dd7a3113544
|
|
BLAKE2b-256 checksum How to use checksums |
3cb947df84cba5fc95e82c2b7c109c8c458203125818f6a21dfd59794490f9e5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Release files / simplibs_rules-0.5.0-py3-none-any.whl
| Download URL | simplibs_rules-0.5.0-py3-none-any.whl |
|---|---|
| Size | 254.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
68845b64738e20a722a65f676a69526cd92e905e54244b2ce3a754aae347eaae
|
|
BLAKE2b-256 checksum How to use checksums |
689333e7db40c3a4625778f53c58ea907b668111476e645c7f50d34047b111ae
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Security for simplibs-rules 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.