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

Arithmetic expressions with powers #20

Closed aaditya-panik closed 3 years ago

aaditya-panik commented 3 years ago

Hi @zeroSteiner

I was going through some expressions and noticed something for arithmetic expressions using powers. The parser parses powers as a float type (mostly because it uses the math.pow method) versus other operators which which result in decimal.Decimal.

https://github.com/zeroSteiner/rule-engine/blob/7a48664ddbfabf7a8aa9b544eab0e9eccda029e0/lib/rule_engine/ast.py#L779

this results in TypeError: unsupported operand type(s) for /: 'decimal.Decimal' and 'float'.

I think this can be resolved by using operator.pow instead of math.pow.

To recreate the error,

python -m rule_engine.debug_repl --edit-console
edit the 'context' and 'thing' objects as necessary
>>> thing = dict(a=8.0,b=2.0)
>>> exit()
exiting the edit console...
rule > a/(b**2)
TypeError: unsupported operand type(s) for /: 'decimal.Decimal' and 'float'
zeroSteiner commented 3 years ago

Yeah you're right, this looks like a bug introduced in 3.0 when the change to using Decimal took place. The math.pow function returns a native float instance instead of a decimal.Decimal instance so it should be updated with the operator.pow as you suggested in the ArithmeticExpression` class..

Thanks for catching this. I'll put together a patch later today.

zeroSteiner commented 3 years ago

Fixed in commit e229063be8e53f6de9790a66354a75d24510e640 which has been released in v3.1.2 and pushed to PyPi.