예제 #1
0
 def eval(self):
     prod = self.value[0].eval()
     for op, val in _operatorOperands(self.value[1:]):
         try:
             if op == '*':
                 prod *= val.eval()
             elif op == '/':
                 prod /= float(val.eval())
         except ZeroDivisionError as e:
             msg = _("ZeroDivisionError: %s") % e
             raise exception.EvaluatorParseException(reason=msg)
     return prod
예제 #2
0
    def eval(self):
        result = self.value
        if (isinstance(result, str)
                and re.match(r"^[a-zA-Z_]+\.[a-zA-Z_]+$", result)):
            (which_dict, entry) = result.split('.')
            try:
                result = _vars[which_dict][entry]
            except KeyError as e:
                msg = _("KeyError: %s") % e
                raise exception.EvaluatorParseException(reason=msg)
            except TypeError as e:
                msg = _("TypeError: %s") % e
                raise exception.EvaluatorParseException(reason=msg)

        try:
            result = int(result)
        except ValueError:
            try:
                result = float(result)
            except ValueError as e:
                msg = _("ValueError: %s") % e
                raise exception.EvaluatorParseException(reason=msg)

        return result
예제 #3
0
def evaluate(expression, **kwargs):
    """Evaluates an expression.

    Provides the facility to evaluate mathematical expressions, and to
    substitute variables from dictionaries into those expressions.

    Supports both integer and floating point values, and automatic
    promotion where necessary.
    """
    global _parser
    if _parser is None:
        _parser = _def_parser()

    global _vars
    _vars = kwargs

    try:
        result = _parser.parseString(expression, parseAll=True)[0]
    except pyparsing.ParseException as e:
        msg = _("ParseException: %s") % e
        raise exception.EvaluatorParseException(reason=msg)

    return result.eval()