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

Negative numbers not supported #52

Closed thedevtoni closed 1 year ago

thedevtoni commented 1 year ago

This is the first time I'm facing this issue. When the context contains a negative number, the matches method throws the error SymbolResolutionError: field_amount in this scenario.

Is there any way to work with negative values or the engine does not support them?

import rule_engine

def type_resolver(name):
    if name == "field_age":
        return rule_engine.DataType.FLOAT
    elif name == "field_amount":
        return rule_engine.DataType.FLOAT
    raise rule_engine.errors.SymbolResolutionError(name)

engine_context = rule_engine.Context(type_resolver=type_resolver)

context = {"field_age": -1}

sentence = "field_age < 0 and field_amount != 4"

rule = rule_engine.Rule(sentence, context=engine_context)
result = rule.matches(context)
zeroSteiner commented 1 year ago

Negative numbers are supported. If I run the code you provided, I get SymboleResolutionError: field_amount which makes sense because you're not defining field_amount in your context. What you pass to rule.matches is supposed to be the thing you're testing, and it needs to provide all of the symbols that your rule (sentence in this example) references.

The only exception is if you set a default value in your engine context, which you are not doing.

Try your example again, but set context to {'field_age': -1, 'field_amount': 0}.

thedevtoni commented 1 year ago

@zeroSteiner thanks for the quick response. Actually using defaults it works.

But also the same code, provide the context as

context = {"field_age": -1}

does not throw. SymbolResolutionError. I was just curious about the difference in this two use cases.

zeroSteiner commented 1 year ago

Yeah those are all different ways to do it. Glad you got it sorted out, I'm going to close this ticket because there's no bug here.