def eval_expr(context, expr, expected_type):
    """
    Eval the provided expression
    :type context: ctx.EvaluationContext
    :param context: Evaluation context.
    :type expr: ast.Expr
    :param expr: The expression to evaluate
    :type expected_type: type_util.IsType
    :param expected_type: The expected type of this computation.
    :rtype: str | float
    :return: Returns the computed value
    """
    if len(expr.expr_tree) == 1:
        return eval_rhs(context, expr.expr_tree[0], expected_type)

    if isinstance(expected_type, type_util.Number):
        result = 0
        cast_func = float
    elif isinstance(expected_type, type_util.String):
        result = ""
        cast_func = str
    else:
        raise exception.BananaEvalBug(
            "Expected type for an expression can only be "
            "'TypeNumber' or 'TypeString', got '{}'".format(
                str(expected_type)))
    current_operator = operator.add
    for el in expr.expr_tree:
        if isinstance(el, basestring) and el in ['+', '-', '*', '/']:
            current_operator = get_op_func(el)
        else:
            value = eval_rhs(context, el, expected_type)
            value = cast_func(value)
            result = current_operator(result, value)
    return result
def get_op_func(op_str):
    if op_str == '+':
        return operator.add
    if op_str == '-':
        return operator.sub
    if op_str == '*':
        return operator.mul
    if op_str == '/':
        return operator.div
    raise exception.BananaEvalBug("Unknown operator '{}'".format(op_str))
Esempio n. 3
0
 def set_variable(self, name, value):
     """Set the variable value."""
     if isinstance(value, tuple) and len(value) == 2:
         comp_type, config = value
         comp_name = name.varname.inner_val()
         self._components[comp_name] = comp_type(comp_name, config)
         self._variables[comp_name] = config
     elif not set_property(self._variables, name, value):
         raise exception.BananaEvalBug(
             "set_variable can only be used with DotPath or Ident.")