Metadata-Version: 2.4
Name: vcti-predicate
Version: 4.0.0
Summary: VCollab Predicate - condition evaluation engine with extensible operators and modifiers
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-predicate
Project-URL: Changelog, https://github.com/vcollab/vcti-python-predicate/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Requires-Dist: numpy; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# vcti-predicate

VCollab Predicate - condition evaluation engine with extensible operators and modifiers

## Overview

Filtering, validation, rule engines and routing logic all need to answer
one question: does this value satisfy this condition? In `vcti-predicate` a
condition is an *op string* (`"=="`, `"^="`, `"between"`, `"is_file"`) that
names a test, applied to one or more arguments, with *modifiers* such as
`case_sensitive` or `tolerance`. The package is built for the usual case,
one rule applied to many values: `condition()` builds a rule once, checking
and preparing its fixed side, so each value costs only its own work.
`check()` and `evaluate()` run a single test. The type of one argument
selects the implementation, so one rule works across strings, numbers,
paths and `None`; it is the first argument unless you mark another with
`by(...)`. Every op string can be negated with a leading `!`, and the
built-in symbols can be extended by building your own registry.

---

## Installation

```bash
pip install vcti-predicate
```

### In `requirements.txt`

```
vcti-predicate>=4.0.0
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-predicate>=4.0.0",
]
```

---

## Quick Start

### One rule, many values

A rule is usually applied to many values: the rows of a file, the records
of a filter. Build it once with `condition`, writing `VALUE` in the place
of the argument that varies, then call it with each value.

```python
from vcti.predicate import VALUE, PredicateError, by, condition

materials = [
    {"name": "Steel", "strength": 520, "rated": (400, 600)},
    {"name": "Aluminium", "strength": 310, "rated": (250, 350)},
    {"name": "Titanium", "strength": 880, "rated": (800, 1000)},
    {"name": "Copper", "strength": 210, "rated": (150, 250)},
]

# A fixed range, a value from each row. by(...) marks the fixed side as the
# one that decides how the test runs, so it is checked and prepared here.
in_range = condition("between", VALUE, by((300, 600)))
in_range(520)                                               # True
[m["name"] for m in materials if in_range(m["strength"])]   # ['Steel', 'Aluminium']

# A fixed value, a range from each row: VALUE can stand for any argument.
rated_for_500 = condition("between", 500, VALUE)
[m["name"] for m in materials if rated_for_500(m["rated"])]   # ['Steel']

# Several rules, built once, applied together to each row.
rules = {"name": condition("^=", VALUE, by("t")), "strength": condition(">", VALUE, by(500))}
[m["name"] for m in materials if all(c(m[f]) for f, c in rules.items())]   # ['Titanium']

# A broken rule fails when it is built, before any row is read.
try:
    condition("between", VALUE, by(300))
except PredicateError as exc:
    print(exc)  # between needs its bounds as a pair (low, high), got 300 ...
```

Building a condition parses the op string, checks the modifiers and the
number of arguments, copies the fixed arguments and prepares them: a range
is ordered, a pattern compiled, a list turned into a lookup. Each call then
does only the work for the new value. A condition gives the same answers
and errors as the single call it stands for, as long as each fixed
argument, with everything it holds, behaves after a deep copy as it did
before. An object that compares by identity (an instance of a class without
`__eq__`) does not: the condition holds a copy, so it never equals the
original. Use `check` when the original object must be passed as it is.

### A single test

```python
from vcti.predicate import check, evaluate

# ── Binary: check(lhs, op_string, rhs) ──

check("Hello", "==", "hello")                        # True: case-insensitive by default
check("Hello", "==", "hello", case_sensitive=True)   # False
check(1.0, "==", 1.001, tolerance=0.01)              # True
check(5, "between", (1, 10))                         # True: bounds in either order

check("filename.pdf", "$=", ".PDF")                  # True: ends with
check("Hello", "^=cs", "he")                         # False: the cs variant is case-sensitive
check("test123", "~=", r"\d+$")                      # True: regex search
check(["Wing", "Tail"], "?=", "wing")                # True: contains

# ── Negation: "!" before any op string ──

check("hello", "!^=", "xyz")    # True
check(0, "!between", (1, 10))   # True

# ── Unary: check(value, op_string) ──

check("", "is_empty")                             # True
check(None, "exists")                             # False
check("12", "is_numeric", numeric_strings=True)   # True
check("TRUE", "is_true")                          # True
check(None, "is_false")                           # True: missing reads as false
check(float("nan"), "is_nan")                     # True
check(".", "is_dir")                              # True

# ── Prefix form, for rules held as data ──

rule = ("^=", "wing")
evaluate(rule[0], "Wing_01", rule[1])   # True
```

Strings and numbers are not mixed unless asked: `check(5, "==", "5")` is
`False`, and `check(5, "==", "5", numeric_strings=True)` is `True`.

---

## Which Argument Decides

A test has to decide how to read its arguments: is `"5.0"` a number or
text? One argument makes that decision, the *selecting* argument: its type
selects the implementation, which then reads the other argument its way.
By default it is the first argument. `by(...)` marks another.

```python
from vcti.predicate import by, check

# The first argument, a string, decides: 5 is read as the text "5".
check("5.0", "==", 5, numeric_strings=True)   # False

# by(...) on the literal: a number decides, so "5.0" is read as 5.0.
check("5.0", "==", by(5), numeric_strings=True)   # True
```

In a rule the fixed side is usually the one that should decide: a rule
`> 500` means a numeric comparison whatever the rows hold. Marking it with
`by(...)` in a condition also lets everything about the rule be checked and
prepared once, when the condition is built. Without `by(...)`, each value
selects, the rule is prepared for every reading a value could ask for, and
an error that only one reading finds is raised when a value of that kind
arrives.

---

## Entry Points

| Function | Argument order | Use case |
|---|---|---|
| `condition(op_string, /, *args, **modifiers)` | op string first, `VALUE` for the varying argument | One rule applied to many values: `condition(">", VALUE, 1200)(size)` |
| `check(value, op_string, /, **modifiers)` | value first | A single unary test, written as code reads |
| `check(lhs, op_string, rhs, /, **modifiers)` | value first | A single binary test |
| `evaluate(op_string, /, *args, **modifiers)` | op string first | A single test for rules held as data, any number of arguments |

All run the same steps: parse the op string, check the modifiers and the
number of arguments, select the operator by the type of the selecting
argument, prepare each argument, and run the test. Everything that depends
only on the rule is checked first, so a broken rule reports the same error
whatever value it meets. A condition does the steps that do not depend on
the varying value once. `builtin_registry` holds the built-in symbols, and
`check`, `evaluate` and `condition` are its methods. A custom `Registry`
has the same methods.

---

## Symbol Summary

| Family | Op strings | Modifiers |
|---|---|---|
| Comparison | `==` `eq`, `<` `lt`, `<=` `le`, `>` `gt`, `>=` `ge`, `between`; `!=` and `ne` negate `==` | `case_sensitive`, `tolerance`, `inclusive`, `allow_nan`, `numeric_strings` |
| String matching | `^=` `startswith`, `$=` `endswith`, `~=` `matches`, each with `cs` and `ic` variants (`^=cs`) | `case_sensitive`, `multiline`, `dotall` |
| Collection items | `?=` `contains` `has`, `?=cs`, `?=ic` | `case_sensitive`, `tolerance`, `allow_nan`, `numeric_strings` |
| Value checks | `is_empty`, `exists` (negated also as `is_none`), `is_numeric`, `is_true`, `is_false`, `is_boolean`, `is_nan`, `is_missing` | `numeric_strings`, `bool_words`, `nonzero_true`, `nan_is_missing` |
| Path checks | `is_file`, `is_dir`, `path_exists` | none |

Every op string has a negated form with a leading `!`: `!^=cs`, `!?=`,
`!is_file`. Every binary symbol can be selected by either argument. The
enum `Symbol` names each symbol (`Symbol.STARTS_WITH`) for code that should
not type strings. The full reference, with what each symbol does for each
type and each selecting argument, is [docs/symbols.md](docs/symbols.md).

---

## Modifiers

| Modifier | Default | Effect |
|---|---|---|
| `case_sensitive` | `False` | Compare strings without casefolding |
| `tolerance` | `0` | Numbers within this absolute difference are equal, also for ordering |
| `inclusive` | `True` | `between` includes its bounds |
| `allow_nan` | `False` | Accept `nan` in a comparison; by default a `nan` raises. Numbers then follow IEEE rules; a string selecting argument compares it as text. Test for `nan` with `is_nan` |
| `numeric_strings` | `False` | Let a string stand in for a number, and a number for a string |
| `multiline`, `dotall` | `False` | `re.MULTILINE` / `re.DOTALL` for `~=` |
| `bool_words` | `False` | `is_true` and friends also read `"yes"`, `"y"`, `"on"` / `"no"`, `"n"`, `"off"` |
| `nonzero_true` | `False` | `is_true` and friends read any non-zero integer as true, not only `1` |
| `nan_is_missing` | `False` | `is_missing` counts `nan` as missing |

A modifier outside the symbol's family raises `ModifierError`, which
catches typos such as `tolernce`. A modifier of the family that the
selected operator does not use is ignored, so one rule works on values of
different types: `tolerance` matters for numbers and not for strings.
These modifiers are the fields of `BuiltinModifiers`, the built-in
registry's modifiers class; a custom registry can subclass it to add its
own (see the [extension guide](docs/extending.md)).

---

## Errors

Every error derives from `PredicateError` and reports the local failure,
with the op string as written (`error.op_string`):

| Error | Raised when |
|---|---|
| `UnknownSymbolError` | The op string is not known |
| `SelectionError` | `VALUE` or `by(...)` is misused, or the symbol cannot be selected by the marked argument |
| `NoOperatorError` | The symbol has no operator for the type of the selecting argument (`None` with `"^="`) |
| `ArityError` | The number of arguments is wrong |
| `ModifierError` | A modifier is unknown, invalid, or disagrees with the op string |
| `CaptureError` | A fixed argument of a condition cannot be copied |
| `OperandError` | An argument is not accepted (`5 < "6"`, a `nan`, bounds that are not a pair); `error.index` is its position |
| `NormalizationError` | An accepted argument cannot be prepared (an invalid regex) |
| `PreparationError` | The base of the four above, and an unexpected failure while preparing |
| `EvaluationError` | The test itself failed (permission denied on `is_file`) |

What an error means is for the caller to decide: a filter can treat
`NoOperatorError` as "no match" and report every other error as a broken
rule.

---

## Dependencies

None. `vcti-predicate` uses only the Python standard library.

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| Look up every symbol and what it does for each type | [docs/symbols.md](docs/symbols.md) |
| See practical, real-world usage | [docs/patterns.md](docs/patterns.md) |
| Understand the architecture and design decisions | [docs/design.md](docs/design.md) |
| Move code from 3.x to 4.0 | [docs/migration-4.0.md](docs/migration-4.0.md) |
| Move code from 2.x to 3.0 | [docs/migration-3.0.md](docs/migration-3.0.md) |
| Navigate and understand the source | [docs/source-guide.md](docs/source-guide.md) |
| Add symbols, groups and operators | [docs/extending.md](docs/extending.md) |
