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
455 stars 54 forks source link

Feature request: Include a plain language description of why the rule failed #75

Open logicbomb opened 1 year ago

logicbomb commented 1 year ago

Expand the return type for matches to be a tuple [bool, str | None] where the 2nd element contains an explaination of the failure when bool = False

It would also be nice to give the rule an optional name e.g.

matched, reason = Rule("flux-capacitor", "foo < 3 and bar == 1" ).matches({"foo": 5, "bar": 1})
# matched: False
# reason: "The flux-capacitor failed because the value of 'foo' is 5, it must be less than 3"

I might be able to take a stab at it, if you think it's a useful feature. I'd want to hammer out how to format multiple failures in a single rule.

logicbomb commented 1 year ago

It may be more flexible to forgo naming the rule and extend the return type to be (bool, list[str] | None), basically return a readable string for each failure,

matched, reasons = Rule("foo < 3 and bar == 2" ).matches({"foo": 5, "bar": 1})
# matched: False
# reasons: ["The value of 'foo' is 5, it must be less than 3", "The value of 'bar' is 1, it must be 2"]
zeroSteiner commented 1 year ago

Yeah that could be interesting. If you do implement it, please add a new function instead of changing the return type of matches to ensure it's backwards compatible. Maybe something like matches_with_reasons, IDK.