A quick single file library for easily adding evaluatable expressions intopython projects. Say you want to allow a user to set an alarm volume, whichcould depend on the time of day, alarm level, how many previous alarms had goneoff, and if there is music playing at the time.

Or if you want to allow simple formulae in a web application, but don't want togive full eval() access, or don't want to run in javascript on the client side.

It's deliberately very simple, pull it in from PyPI (pip or easy_install), oreven just a single file you can dump into a project.

Internally, it's using the amazing python ``ast`` module to parse theexpression, which allows very fine control of what is and isn't allowed. Itshould be completely safe in terms of what operations can be performed by theexpression.

The only issue I know to be aware of is that you can create an expression whichtakes a long time to evaluate, or which evaluating requires an awful lot ofmemory, which leaves the potential for DOS attacks. There is basic protectionagainst this, and you can lock it down further if you desire. (see theOperators_ section below)

You should be aware of this when deploying in a public setting.

The defaults are pretty locked down and basic, and it's very easy to addwhatever extra specific functionality you need (your own functions,variable/name lookup, etc).

Basic Usage-----------

To get very simple evaluating:

.. code-block:: python

from simpleeval import simple_eval

simple_eval("21 + 21")

returns ``42``.

Expressions can be as complex and convoluted as you want:

.. code-block:: python

simple_eval("21 + 19 / 7 + (8 % 3) ** 9")

returns ``535.714285714``.

You can add your own functions in as well.

.. code-block:: python

simple_eval("square(11)", functions={"square": lambda x: x*x})

returns ``121``.

For more details of working with functions, read further down.

Note:~~~~~all further examples use ``>>>`` to designate python code, as if you are usingthe python interactive prompt.

.. _Operators:

Operators---------You can add operators yourself, using the ``operators`` argument, but these arethe defaults:

The ``^`` operator is notably missing - not because it's hard, but because itis often mistaken for a exponent operator, not the bitwise operation that it isin python. It's trivial to add back in again if you wish (using the classbased evaluator explained below):

.. code-block:: python

>>> import ast >>> import operator

>>> s = SimpleEval() >>> s.operators[ast.BitXor] = operator.xor

>>> s.eval("2 ^ 10") 8

Limited Power~~~~~~~~~~~~~

Also note, the ``**`` operator has been locked down by default to have amaximum input value of ``4000000``, which makes it somewhat harder to makeexpressions which go on for ever. You can change this limit by changing the``simpleeval.POWER_MAX`` module level value to whatever is an appropriate valuefor you (and the hardware that you're running on) or if you want to completelyremove all limitations, you can set the ``s.operators[ast.Pow] = operator.pow``or make your own function.

On my computer, ``9**9**5`` evaluates almost instantly, but ``9**9**6`` takesover 30 seconds. Since ``9**7`` is ``4782969``, and so over the ``POWER_MAX``limit, it throws a ``NumberTooHigh`` exception for you. (Otherwise it would goon for hours, or until the computer runs out of memory)

Strings (and other Iterables) Safety~~~~~~~~~~~~~

There are also limits on string length (100000 characters,``MAX_STRING_LENGTH``). This can be changed if you wish.

Related to this, if you try to create a silly long string/bytes/list, by doing``'i want to break free'.split() * 9999999999`` for instance, it will block you.

Sometimes it's useful to have variables available, which in python terminologyare called 'names'.

.. code-block:: python

>>> simple_eval("a + b", names={"a": 11, "b": 100}) 111

You can also hand the handling of names over to a function, if you prefer:

.. code-block:: python

>>> def name_handler(node): return ord(node.id[0].lower(a))-96

>>> simple_eval('a + b', names=name_handler) 3

That was a bit of a silly example, but you could use this for pulling valuesfrom a database or file, say, or doing some kind of caching system.

The two default names that are provided are ``True`` and ``False``. So if you want to provide your own names, but want ``True`` and ``False`` to keep working, either provide them yourself, or ``.copy()`` and ``.update`` the ``DEFAULT_NAMES``. (See functions example above).

Creating an Evaluator Class---------------------------

Rather than creating a new evaluator each time, if you are doing a lot ofevaluations, you can create a SimpleEval object, and pass it expressions eachtime (which should be a bit quicker, and certainly more convenient for some usecases):

.. code-block:: python

>>> s = SimpleEval()

>>> s.eval("1 + 1") 2

>>> s.eval('100 * 10') 1000

# and so on...

You can assign / edit the various options of the ``SimpleEval`` object if youwant to. Either assign them during creation (like the ``simple_eval``function)

.. code-block:: python

def boo(): return 'Boo!'

s = SimpleEval(functions={"boo": boo})

or edit them after creation:

.. code-block:: python

s.names['fortytwo'] = 42

this actually means you can modify names (or functions) with functions, if youreally feel so inclined:

Say. This would allow a certain level of 'scriptyness' if you had theseevaluations happening as callbacks in a program. Although you really arereaching the end of what this library is intended for at this stage.

Compound Types--------------

Compound types (``dict``, ``tuple``, ``list``, ``set``) in general just work ifyou pass them in as named objects. If you want to allow creation of these, the``EvalWithCompoundTypes`` class works. Just replace any use of ``SimpleEval`` withthat.

Extending---------

The ``SimpleEval`` class is pretty easy to extend. For instance, to create aversion that disallows method invocation on objects: