rule-engine Expression Language
rule-engine is a lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects. It provides a simple way to define and evaluate complex rules against data, supporting various data types and custom functions. The current stable version is 4.5.3, with frequent patch releases and a v5 alpha in active development.
Warnings
- breaking Version 5.0.0 is in alpha (v5.0.0a1 has been released) and introduces significant breaking changes and API refactors. Do not update to v5.x without thoroughly reviewing the changelog and migrating your code.
- gotcha From v4.5.0 onwards, rule-engine is stricter about invalid string literals and function return types. `StringSyntaxError` is now raised for malformed string literals and `FunctionCallError` for type-incompatible function returns, where previous versions might have had different behavior.
- gotcha The backslash character (`\`) is used for escaping in rule strings. If you need a literal backslash in your rule (e.g., in a regex pattern or string literal), you must double-escape it (e.g., `\\`).
- gotcha When defining custom functions or interacting with complex Python objects, ensure you correctly use `Context` and `DataType` objects. Incorrect type declarations or context setup can lead to unexpected `FunctionCallError` or evaluation issues.
Install
-
pip install rule-engine
Imports
- Rule
from rule_engine import Rule
- Context
from rule_engine import Context
- DataType
from rule_engine import DataType
Quickstart
from rule_engine import Rule
# Define a rule with an expression string
rule = Rule('sum(items) > 100 && "apple" in items')
# Evaluate the rule against different data contexts
print(f"Result 1: {rule.matches({'items': [10, 20, 30, 40, 50, "apple"]})})")
print(f"Result 2: {rule.matches({'items': [10, 20, "orange"]})})")