How to use the simpleeval.DEFAULT_FUNCTIONS function in simpleeval

To help you get started, we’ve selected a few simpleeval examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github danthedeckie / simpleeval / test_simpleeval.py View on Github external
exec('DISALLOWED.append(exec)') # exec is not a function in Python2...

        for f in simpleeval.DISALLOW_FUNCTIONS:
            assert f in DISALLOWED


        DF = simpleeval.DEFAULT_FUNCTIONS.copy()

        for x in DISALLOWED:
            simpleeval.DEFAULT_FUNCTIONS = DF.copy()
            with self.assertRaises(FeatureNotAvailable):
                s = SimpleEval()
                s.functions['foo'] = x
                s.eval('foo(42)')

        simpleeval.DEFAULT_FUNCTIONS = DF.copy()
github danthedeckie / simpleeval / test_simpleeval.py View on Github external
with open(filename) as f2:
                return f2.read()

        # simple load:

        self.s.functions = {"read": load_file}
        self.t("read('testfile.txt')", "42")

        # and we should have *replaced* the default functions. Let's check:

        with self.assertRaises(simpleeval.FunctionNotDefined):
            self.t("int(read('testfile.txt'))", 42)

        # OK, so we can load in the default functions as well...

        self.s.functions.update(simpleeval.DEFAULT_FUNCTIONS)

        # now it works:

        self.t("int(read('testfile.txt'))", 42)

        os.remove('testfile.txt')
github dimagi / commcare-hq / corehq / apps / userreports / expressions / utils.py View on Github external
def safe_pow_fn(a, b):
    raise InvalidExpression


def safe_range(start, *args):
    ret = list(range(start, *args))
    if len(ret) < 100:
        return ret
    return None


SAFE_OPERATORS = copy.copy(DEFAULT_OPERATORS)
SAFE_OPERATORS[ast.Pow] = safe_pow_fn  # don't allow power operations

FUNCTIONS = DEFAULT_FUNCTIONS
FUNCTIONS.update({
    'timedelta_to_seconds': lambda x: x.total_seconds() if isinstance(x, timedelta) else None,
    'range': safe_range
})


def eval_statements(statement, variable_context):
    """Evaluates math statements and returns the value

    args
        statement: a simple python-like math statement
        variable_context: a dict with variable names as key and assigned values as dict values
    """
    # variable values should be numbers
    var_types = set(type(value) for value in variable_context.values())
    if not var_types.issubset({float, Decimal, date, datetime, NoneType, bool}.union(set(six.integer_types))):