mpacts.core.units. units_eval

An expression evaluator to be used as a safe replacement for builtin eval.

copyright:2016 by Pint Authors, see AUTHORS for more details.
license:BSD, see LICENSE for more details.

In order to be able to use this module import it like this:

import mpacts.core.units.units_eval
#or assign it to a shorter name
import mpacts.core.units.units_eval as uni

EvalTreeNode

class mpacts.core.units.units_eval.EvalTreeNode(left, operator=None, right=None)

Bases: object

left + operator + right –> binary op left + operator –> unary op left + right –> implicit op left –> single value

EvalTreeNode(name, parent, **kwargs)
evaluate(define_op, bin_op={'': <built-in function mul>, '+': <built-in function add>, '*': <built-in function mul>, '-': <built-in function sub>, '/': <built-in function truediv>, '**': <built-in function pow>}, un_op={'+': <function <lambda> at 0x2aacbc66d398>, '-': <function <lambda> at 0x2aacbc66d410>})

define_op is a callable that translates tokens into objects bin_op and un_op provide functions for performing binary and unary operations

to_string()
mpacts.core.units.units_eval.build_eval_tree(tokens, op_priority={'unary': 2, '': 1, '**': 3, '+': 0, '*': 1, '-': 0, '/': 1, '^': 3}, index=0, depth=0, prev_op=None)

Params: Index, depth, and prev_op used recursively, so don’t touch. Tokens is an iterable of tokens from an expression to be evaluated.

Transform the tokens from an expression into a recursive parse tree, following order of operations. Operations can include binary ops (3 + 4), implicit ops (3 kg), or unary ops (-1).

General Strategy: 1) Get left side of operator 2) If no tokens left, return final result 3) Get operator 4) Use recursion to create tree starting at token on right side of operator (start at step #1) 4.1) If recursive call encounters an operator with lower or equal priority to step #2, exit recursion 5) Combine left side, operator, and right side into a new left side 6) Go back to step #2