How to use the simpleeval.SimpleEval 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 gil9red / SimplePyScripts / simpleeval__examples__calc / hello_world.py View on Github external
print(simple_eval("abs(sin(3) * cos(3))", functions={'sin': math.sin, 'cos': math.cos, 'abs': abs}))  # 0.13970774909946293


def my_md5(value):
    import hashlib
    return hashlib.md5(bytes(value, 'utf-8')).hexdigest()


print(simple_eval("md5('Hello World!')", functions={'md5': my_md5}))  # ed076287532e86365e841e92bfc50d8c
print(simple_eval("list('1234')", functions={'list': list}))  # ['1', '2', '3', '4']
print()

# Using SimpleEval class
from simpleeval import SimpleEval

my_eval = SimpleEval()
my_eval.names['a'] = 2
my_eval.functions['square'] = lambda x: x * x

print(my_eval.eval('1 + 1 * a'))          # 3
print(my_eval.eval('square(1 + 1 * a)'))  # 9
github KurtJacobson / hazzy / hazzy / main_old.py View on Github external
# Components needed to communicate with hal and linuxcnc
        self.hal = hal.component('hazzy')
        self.command = linuxcnc.command()
        self.stat = linuxcnc.stat()
        self.error_channel = linuxcnc.error_channel()

        # Norbert's module to get information from the ini file
        self.get_ini_info = getiniinfo.GetIniInfo()

        # Module to get/set preferences
        pref_file = self.get_ini_info.get_preference_file_path()
        self.prefs = preferences.Preferences
        self.prefs.set_file_path(pref_file)

        # Module used to evaluate expressions in entries
        self.s = simpleeval.SimpleEval()

        # Hazzy Modules init
        self.gcode_view = GcodeView(preview=False)
        self.gcode_preview = GcodeView(preview=True)
        #self.float_touchpad = Touchpad("float")
        #self.int_touchpad = Touchpad("int")
        self.keyboard = Keyboard
        self.keyboard.set_parent(self.window)
        self.filechooser = Filechooser()
        self.yes_no_dialog = Dialogs(DialogTypes.YES_NO)
        self.error_dialog = Dialogs(DialogTypes.ERROR)

        # Get the tool table liststore
        self.tool_liststore = self.builder.get_object("tool_liststore")
github gil9red / SimplePyScripts / simpleeval__examples__calc / operators__user_custom__only__add_and_sub.py View on Github external
SUPPORTED_OPERATORS = {
    ast.Add: op.add,
    ast.Sub: op.sub,
}


print(simple_eval("2 + 2 - 1", operators=SUPPORTED_OPERATORS))  # 3

try:
    print(simple_eval("2 + 2 * 2", operators=SUPPORTED_OPERATORS))  # KeyError: 
except Exception as e:
    print(repr(e))

print()

s = SimpleEval(operators=SUPPORTED_OPERATORS)
# # OR:
# s = SimpleEval()
# s.operators = SUPPORTED_OPERATORS

print(s.eval("2 + 2 - 1"))  # 3

try:
    print(s.eval("2 + 2 * 2"))  # KeyError: 
except Exception as e:
    print(repr(e))
github KurtJacobson / hazzy / hazzy / utilities / entryeval.py View on Github external
def __init__(self):
        self.s = SimpleEval()

        try:
            ini = GetIniInfo()
            self.machine_metric = ini.get_machine_metric()
        except:
            # GetIniInfo instance has no __call__ method
            self.machine_metric = False
            log.info('INI file not available, assuming machine units inch')
github gil9red / SimplePyScripts / simpleeval__examples__calc / basic / operators__user_custom.py View on Github external
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'


# SOURCE: https://github.com/danthedeckie/simpleeval#operators


# pip install simpleeval
from simpleeval import SimpleEval

import ast
import operator as op


s = SimpleEval()
s.operators[ast.BitXor] = op.xor
# # OR:
# s.operators[ast.BitXor] = lambda a, b: a ^ b

print(s.eval("2 ^ 10"))  # 8
github danthedeckie / simpleeval / simpleeval.py View on Github external
evaluated_values = []
        for n in node.values:
            val = str(self._eval(n))
            if len(val) + length > MAX_STRING_LENGTH:
                raise IterableTooLong("Sorry, I will not evaluate something this long.")
            evaluated_values.append(val)
        return ''.join(evaluated_values)

    def _eval_formattedvalue(self, node):
        if node.format_spec:
            fmt = "{:" + self._eval(node.format_spec) + "}"
            return fmt.format(self._eval(node.value))
        return self._eval(node.value)


class EvalWithCompoundTypes(SimpleEval):
    """
        SimpleEval with additional Compound Types, and their respective
        function editions. (list, tuple, dict, set).
    """

    def __init__(self, operators=None, functions=None, names=None):
        super(EvalWithCompoundTypes, self).__init__(operators, functions, names)

        self.functions.update(
            list=list,
            tuple=tuple,
            dict=dict,
            set=set)

        self.nodes.update({
            ast.Dict: self._eval_dict,
github gil9red / SimplePyScripts / simpleeval__examples__calc / simple_eval__hashlib__override_eval_call.py View on Github external
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'


# pip install simpleeval
from simpleeval import SimpleEval

import hashlib

from simple_eval__hashlib__fill_functions import hashlib_func


class SimpleHashlibEval(SimpleEval):
    def _eval_call(self, node):
        name = node.func.id.lower()

        # Case-insensitive call func and check argument
        if name in hashlib.algorithms_guaranteed and node.args:
            value = self._eval(node.args[0])
            return hashlib_func(value, name)

        return super()._eval_call(node)


if __name__ == '__main__':
    hashlib_eval = SimpleHashlibEval()

    print(hashlib_eval.eval('md5("Hello World!")'))     # ed076287532e86365e841e92bfc50d8c
    print(hashlib_eval.eval('sha1("Hello World!")'))    # 2ef7bde608ce5404e97d5f042f95f89f1c232871
github danthedeckie / simpleeval / simpleeval.py View on Github external
def simple_eval(expr, operators=None, functions=None, names=None):
    """ Simply evaluate an expresssion """
    s = SimpleEval(operators=operators,
                   functions=functions,
                   names=names)
    return s.eval(expr)
github gil9red / SimplePyScripts / simpleeval__examples__calc / basic / compound_types.py View on Github external
# SimpleEval with that.
# """


# pip install simpleeval
from simpleeval import simple_eval, SimpleEval, EvalWithCompoundTypes


# SimpleEval and simple_eval NOT WORK with compound types
try:
    print(simple_eval('[1, 2, 3, 4]'))
except Exception as e:
    print(e)  # Sorry, List is not available in this evaluator

try:
    my_eval = SimpleEval()
    print(my_eval.eval('[1, 2, 3, 4]'))
except Exception as e:
    print(e)  # Sorry, List is not available in this evaluator

print()

# Compound Types
my_compound_types_eval = EvalWithCompoundTypes()
my_compound_types_eval.functions['len'] = len

# list
print(my_compound_types_eval.eval('[1, 2, 3, 4]'))              # [1, 2, 3, 4]
print(my_compound_types_eval.eval('[1, 2] + [3, 4]'))           # [1, 2, 3, 4]
print(my_compound_types_eval.eval('len([1, 2, 3, 4])'))         # 4
print(my_compound_types_eval.eval('[1, 2, 1, 3, 4].count(1)'))  # 2
print(my_compound_types_eval.eval('list("1234")'))              # ['1', '2', '3', '4']