zeroSteiner / rule-engine

A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.
https://zerosteiner.github.io/rule-engine/
BSD 3-Clause "New" or "Revised" License
433 stars 54 forks source link

how to add custom function in rule engine #89

Closed clevertension closed 3 months ago

clevertension commented 3 months ago

i search the code, and the buildins can't add my custome function

i just want like

myfunc(first_name) == "Luke"

image
zeroSteiner commented 3 months ago

What you're looking at are the builtin functions that use the $ prefix. There's documentation here on how to add your own or override what the package provides by default.

If you don't want it to be a builtin function that uses the $ prefix, you'd just pass it into the rule with the other data you're evaluating.

PYTHONPATH=$(pwd)/lib python -m rule_engine.debug_repl --edit-console
edit the 'context' and 'thing' objects as necessary
>>> thing = {'mysum': sum}  
>>> 
exiting the edit console...
rule > mysum([1, 2])
result: 
Decimal('3')
rule > 
clevertension commented 3 months ago

oh, this engine is powerful, i find that is easy to add custome function, see the following code

def check_cross_rectangle(rect1, rect2):
    print('rect1 =', rect1)
    print('rect2 =', rect2)
    # do your custom check
    return True

check_item = {'check_func': check_cross_rectangle, 'rect1': [1, 2, 3, 4], 'rect2': [5, 6, 7, 8]}
rule = engine.Rule('check_func(rect1, rect2)')
result = rule.matches(check_item)
self.assertTrue(result, "the expected two rectangles should be crossed")

@zeroSteiner thank you very much