danthedeckie / simpleeval

Simple Safe Sandboxed Extensible Expression Evaluator for Python
Other
451 stars 85 forks source link

Decimal support example not working #74

Closed scrwghub closed 4 years ago

scrwghub commented 4 years ago

Hi, in this issue you propose a solution for using simpleeval with Decimal type. That appears to no longer be working? I'm not quite sure why.

import decimal
import simpleeval

class DecimalEval(simpleeval.SimpleEval):
    @staticmethod
    def _eval_num(node):
        return decimal.Decimal(node.n)

decimal.getcontext().prec = 1

print(DecimalEval().eval('0.1+0.2'))
print(type(DecimalEval().eval('0.1+0.2')))

This outputs

0.30000000000000004
<class 'float'>

Can you give some insight please?

scrwghub commented 4 years ago

Solved it myself. It will work if I use _eval_constant instead of _eval_num, for python >=3.8.