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

Are triggers supported? #47

Closed radiantone closed 1 year ago

radiantone commented 1 year ago

For example, when a rule is matched, call a function?

zeroSteiner commented 1 year ago

You could just call whatever function you want:

if rule.matches(thing):
    callback()

If you wanted to get fancy, you could define your own Rule class pretty easily.

class MyRule(rule_engine.Rule):
    def evaluate(self, thing):
        result = super().evaluate(thing)
        if result:
            callback()
        return result

Override, evaluate not matches.

radiantone commented 1 year ago

Yeah, but then I'm back to using if/thens. What I would want is for the rules engine to trigger within its evaluation such that I don't have to use if/thens afterwards otherwise I'm adding back the problem I'm trying to solve (not using nested if/thens)

zeroSteiner commented 1 year ago

Yeah, the second solution then is probably what you want. Define your own rule that extends the rule_engine.Rule class and does whatever you'd like on evaluation by overriding the evaluate method. You might also want to override __init__ to define the callback as well if it's rule-specific. If the callback is thing-specific and you have multiple rules, you could probably make use of map, filter and list comprehension.