A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.
npx @tessl/cli install tessl/pypi-rule-engine@4.5.00
# Rule Engine
1
2
A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects. Rule Engine provides a powerful system for evaluating custom expressions against Python data structures with type safety, error handling, and extensibility.
3
4
## Package Information
5
6
- **Package Name**: rule-engine
7
- **Language**: Python
8
- **Installation**: `pip install rule-engine`
9
- **Version**: 4.5.3
10
11
## Core Imports
12
13
```python
14
import rule_engine
15
```
16
17
Common import pattern for main classes:
18
19
```python
20
from rule_engine import Rule, Context, DataType
21
```
22
23
All functionality is available from the main module:
24
25
```python
26
from rule_engine import (
27
Rule, Context, DataType,
28
resolve_attribute, resolve_item, type_resolver_from_dict,
29
EngineError, RuleSyntaxError, EvaluationError
30
)
31
```
32
33
## Basic Usage
34
35
```python
36
import rule_engine
37
38
# Basic rule creation and evaluation
39
rule = rule_engine.Rule('first_name == "Luke" and age > 18')
40
data = {'first_name': 'Luke', 'last_name': 'Skywalker', 'age': 25}
41
42
# Check if data matches the rule
43
if rule.matches(data):
44
print("Match found!")
45
46
# Filter a collection of objects
47
people = [
48
{'first_name': 'Luke', 'age': 25},
49
{'first_name': 'Leia', 'age': 25},
50
{'first_name': 'Han', 'age': 32}
51
]
52
53
adults = list(rule.filter(people))
54
print(f"Found {len(adults)} adults")
55
56
# Using typed context for type safety
57
context = rule_engine.Context(
58
type_resolver=rule_engine.type_resolver_from_dict({
59
'first_name': rule_engine.DataType.STRING,
60
'age': rule_engine.DataType.FLOAT
61
})
62
)
63
64
typed_rule = rule_engine.Rule('first_name + " is " + str(age)', context=context)
65
result = typed_rule.evaluate(data)
66
print(result) # "Luke is 25"
67
```
68
69
## Architecture
70
71
Rule Engine uses a multi-layered architecture:
72
73
- **Parser**: PLY-based parser for rule expression grammar with lexical analysis
74
- **AST**: Abstract syntax tree representation of parsed expressions with type checking
75
- **Engine**: Core evaluation engine with context management and symbol resolution
76
- **Type System**: Comprehensive type system with DataType constants and type checking
77
- **Error Handling**: Hierarchical exception system for syntax and evaluation errors
78
79
The design enables flexible symbol resolution, optional type safety, thread safety, and extensibility for custom contexts and resolvers.
80
81
## Capabilities
82
83
### Core Rule Operations
84
85
The fundamental rule evaluation system including rule creation, matching, filtering, and expression evaluation. These operations form the foundation of the rule engine's functionality.
86
87
```python { .api }
88
class Rule:
89
def __init__(self, rule_text: str, context: Context = None): ...
90
def matches(self, thing, **kwargs) -> bool: ...
91
def filter(self, things, **kwargs): ...
92
def evaluate(self, thing, **kwargs): ...
93
94
@property
95
def text(self) -> str: ...
96
@property
97
def context(self) -> Context: ...
98
```
99
100
[Core Operations](./core-operations.md)
101
102
### Context and Symbol Resolution
103
104
Context management system for controlling how symbols are resolved and type checking is performed. Includes custom resolver functions and type validation.
105
106
```python { .api }
107
class Context:
108
def __init__(self, type_resolver=None, resolver=None, default_value=None): ...
109
def resolve(self, name: str, object_instance=None): ...
110
111
def resolve_attribute(thing, name: str): ...
112
def resolve_item(thing, name: str): ...
113
def type_resolver_from_dict(dictionary: dict): ...
114
```
115
116
[Context Management](./context-management.md)
117
118
### Type System
119
120
Comprehensive type system with DataType constants for all supported data types, type checking utilities, and type coercion functions.
121
122
```python { .api }
123
class DataType:
124
ARRAY: DataType
125
BYTES: DataType
126
BOOLEAN: DataType
127
DATETIME: DataType
128
FLOAT: DataType
129
FUNCTION: DataType
130
MAPPING: DataType
131
NULL: DataType
132
SET: DataType
133
STRING: DataType
134
TIMEDELTA: DataType
135
UNDEFINED: DataType
136
137
@classmethod
138
def from_name(cls, name: str): ...
139
@classmethod
140
def from_type(cls, python_type): ...
141
@classmethod
142
def from_value(cls, python_value): ...
143
@classmethod
144
def is_compatible(cls, dt1, dt2) -> bool: ...
145
```
146
147
[Type System](./type-system.md)
148
149
### Error Handling
150
151
Hierarchical exception system covering syntax errors, evaluation errors, type mismatches, and symbol resolution failures with detailed error information and suggestions.
152
153
```python { .api }
154
class EngineError(Exception): ...
155
class EvaluationError(EngineError): ...
156
class RuleSyntaxError(EngineError): ...
157
class SymbolResolutionError(EvaluationError): ...
158
class AttributeResolutionError(EvaluationError): ...
159
```
160
161
[Error Handling](./error-handling.md)
162
163
## Expression Language Features
164
165
Rule Engine supports a rich expression language with:
166
167
- **Data types**: strings, numbers, booleans, datetime, timedelta, arrays, mappings, sets, bytes
168
- **Operators**: arithmetic (+, -, *, /, %, **), comparison (==, !=, <, >, <=, >=), logical (and, or, not)
169
- **Regular expressions**: string matching with =~ and !~ operators
170
- **Built-in functions**: abs, all, any, filter, map, max, min, parse_datetime, parse_float, parse_timedelta, random, range, split, sum
171
- **Built-in constants**: e (mathematical constant), pi (mathematical constant), now (current datetime), today (current date)
172
- **Data access**: attribute access (obj.attr), item access (obj['key']), nested access
173
- **Type hints**: optional type annotations for symbols and return values
174
- **Ternary operator**: conditional expressions (condition ? true_value : false_value)
175
176
## Thread Safety
177
178
Rule Engine is designed to be thread-safe. Rule objects can be shared across threads, and evaluation operations are safe for concurrent use. Context objects and type resolvers are also thread-safe.
179
180
## Debug REPL
181
182
Rule Engine includes an interactive debug REPL for experimentation:
183
184
```bash
185
python -m rule_engine.debug_repl
186
```
187
188
The REPL provides:
189
- Interactive rule evaluation and testing
190
- Symbol inspection and type checking
191
- AST visualization and debugging
192
- Error analysis and troubleshooting