simpleeval


Namesimpleeval JSON
Version 0.9.12 PyPI version JSON
download
home_pagehttps://github.com/danthedeckie/simpleeval
SummaryA simple, safe single expression evaluator library.
upload_time2022-01-15 17:32:55
maintainer
docs_urlNone
authorDaniel Fairhead
requires_python
license
keywords eval simple expression parse ast
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            simpleeval (Simple Eval)
========================

.. image:: https://github.com/danthedeckie/simpleeval/actions/workflows/ci.yml/badge.svg?branch=gh-actions-build
   :target: https://github.com/danthedeckie/simpleeval/actions/
   :alt: Build Status

.. image:: https://codecov.io/gh/danthedeckie/simpleeval/branch/master/graph/badge.svg?token=isRnN1yrca
   :target: https://codecov.io/gh/danthedeckie/simpleeval
   :alt: Code Coverage

.. image:: https://badge.fury.io/py/simpleeval.svg
   :target: https://badge.fury.io/py/simpleeval
   :alt: PyPI Version

A quick single file library for easily adding evaluatable expressions into
python projects.  Say you want to allow a user to set an alarm volume, which
could depend on the time of day, alarm level, how many previous alarms had gone
off, 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 to
give 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), or
even just a single file you can dump into a project.

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

The only issue I know to be aware of is that you can create an expression which
takes a long time to evaluate, or which evaluating requires an awful lot of
memory, which leaves the potential for DOS attacks.  There is basic protection
against this, and you can lock it down further if you desire. (see the
Operators_ 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 add
whatever 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 using
the python interactive prompt.

.. _Operators:

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

+--------+------------------------------------+
|  ``+`` | add two things. ``x + y``          |
|        | ``1 + 1`` -> ``2``                 |
+--------+------------------------------------+
|  ``-`` | subtract two things ``x - y``      |
|        | ``100 - 1`` -> ``99``              |
+--------+------------------------------------+
|  ``/`` | divide one thing by another        |
|        | ``x / y``                          |
|        | ``100/10`` -> ``10``               |
+--------+------------------------------------+
|  ``*`` | multiple one thing by another      |
|        | ``x * y``                          |
|        | ``10 * 10`` -> ``100``             |
+--------+------------------------------------+
| ``**`` | 'to the power of' ``x**y``         |
|        | ``2 ** 10`` -> ``1024``            |
+--------+------------------------------------+
| ``%``  | modulus. (remainder)  ``x % y``    |
|        | ``15 % 4`` -> ``3``                |
+--------+------------------------------------+
| ``==`` | equals  ``x == y``                 |
|        | ``15 == 4`` -> ``False``           |
+--------+------------------------------------+
| ``<``  | Less than. ``x < y``               |
|        | ``1 < 4`` -> ``True``              |
+--------+------------------------------------+
| ``>``  | Greater than. ``x > y``            |
|        | ``1 > 4`` -> ``False``             |
+--------+------------------------------------+
| ``<=`` | Less than or Equal to. ``x <= y``  |
|        | ``1 < 4`` -> ``True``              |
+--------+------------------------------------+
| ``>=`` | Greater or Equal to ``x >= 21``    |
|        | ``1 >= 4`` -> ``False``            |
+--------+------------------------------------+
| ``>>`` | "Right shift" the number.          |
|        | ``100 >> 2`` -> ``25``             |
+--------+------------------------------------+
| ``<<`` | "Left shift" the number.           |
|        | ``100 << 2`` -> ``400``            |
+--------+------------------------------------+
| ``in`` | is something contained within      |
|        | something else.                    |
|        | ``"spam" in "my breakfast"``       |
|        | -> ``False``                       |
+--------+------------------------------------+


The ``^`` operator is notably missing - not because it's hard, but because it
is often mistaken for a exponent operator, not the bitwise operation that it is
in python.  It's trivial to add back in again if you wish (using the class
based 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 a
maximum input value of ``4000000``, which makes it somewhat harder to make
expressions which go on for ever.  You can change this limit by changing the
``simpleeval.POWER_MAX`` module level value to whatever is an appropriate value
for you (and the hardware that you're running on) or if you want to completely
remove 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`` takes
over 30 seconds.  Since ``9**7`` is ``4782969``, and so over the ``POWER_MAX``
limit, it throws a ``NumberTooHigh`` exception for you. (Otherwise it would go
on 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.

If Expressions
--------------

You can use python style ``if x then y else z`` type expressions:

.. code-block:: python

    >>> simple_eval("'equal' if x == y else 'not equal'",
                    names={"x": 1, "y": 2})
    'not equal'

which, of course, can be nested:

.. code-block:: python

    >>> simple_eval("'a' if 1 == 2 else 'b' if 2 == 3 else 'c'")
    'c'


Functions
---------

You can define functions which you'd like the expresssions to have access to:

.. code-block:: python

    >>> simple_eval("double(21)", functions={"double": lambda x:x*2})
    42

You can define "real" functions to pass in rather than lambdas, of course too,
and even re-name them so that expressions can be shorter

.. code-block:: python

    >>> def double(x):
            return x * 2
    >>> simple_eval("d(100) + double(1)", functions={"d": double, "double":double})
    202

If you don't provide your own ``functions`` dict, then the the following defaults
are provided in the ``DEFAULT_FUNCTIONS`` dict:

+----------------+--------------------------------------------------+
| ``randint(x)`` | Return a random ``int`` below ``x``              |
+----------------+--------------------------------------------------+
| ``rand()``     | Return a random ``float`` between 0 and 1        |
+----------------+--------------------------------------------------+
| ``int(x)``     | Convert ``x`` to an ``int``.                     |
+----------------+--------------------------------------------------+
| ``float(x)``   | Convert ``x`` to a ``float``.                    |
+----------------+--------------------------------------------------+
| ``str(x)``     | Convert ``x`` to a ``str`` (``unicode`` in py2)  |
+----------------+--------------------------------------------------+

If you want to provide a list of functions, but want to keep these as well,
then you can do a normal python ``.copy()`` & ``.update``:

.. code-block:: python

    >>> my_functions = simpleeval.DEFAULT_FUNCTIONS.copy()
    >>> my_functions.update(
            square=(lambda x:x*x),
            double=(lambda x:x+x),
        )
    >>> simple_eval('square(randint(100))', functions=my_functions)

Names
-----

Sometimes it's useful to have variables available, which in python terminology
are 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 values
from 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 of
evaluations, you can create a SimpleEval object, and pass it expressions each
time (which should be a bit quicker, and certainly more convenient for some use
cases):

.. 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 you
want 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 you
really feel so inclined:

.. code-block:: python

    s = SimpleEval()
    def set_val(name, value):
        s.names[name.value] = value.value
        return value.value

    s.functions = {'set': set_val}

    s.eval("set('age', 111)")

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

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

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

The ``EvalWithCompoundTypes`` class also contains support for simple comprehensions.
eg: ``[x + 1 for x in [1,2,3]]``.  There's a safety `MAX_COMPREHENSION_LENGTH` to control
how many items it'll allow before bailing too.  This also takes into account nested
comprehensions.

Since the primary intention of this library is short expressions - an extra 'sweetener' is
enabled by default.  You can access a dict (or similar's) keys using the .attr syntax:

.. code-block:: python

    >>>  simple_eval("foo.bar", names={"foo": {"bar": 42}})
    42

for instance.  You can turn this off either by setting the module global `ATTR_INDEX_FALLBACK`
to `False`, or on the ``SimpleEval`` instance itself. e.g. ``evaller.ATTR_INDEX_FALLBACK=False``.

Extending
---------

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

.. code-block:: python

    import ast
    import simpleeval

    class EvalNoMethods(simpleeval.SimpleEval):
        def _eval_call(self, node):
            if isinstance(node.func, ast.Attribute):
                raise simpleeval.FeatureNotAvailable("No methods please, we're British")
            return super(EvalNoMethods, self)._eval_call(node)

and then use ``EvalNoMethods`` instead of the ``SimpleEval`` class.

Other...
--------

The library supports python 3 - but should be mostly compatible (and tested before 0.9.11)
with python 2.7 as well.

Object attributes that start with ``_`` or ``func_`` are disallowed by default.
If you really need that (BE CAREFUL!), then modify the module global
``simpleeval.DISALLOW_PREFIXES``.

A few builtin functions are listed in ``simpleeval.DISALLOW_FUNCTIONS``.  ``type``, ``open``, etc.
If you need to give access to this kind of functionality to your expressions, then be very
careful.  You'd be better wrapping the functions in your own safe wrappers.

The initial idea came from J.F. Sebastian on Stack Overflow
( http://stackoverflow.com/a/9558001/1973500 ) with modifications and many improvements,
see the head of the main file for contributors list.

Please read the ``test_simpleeval.py`` file for other potential gotchas or
details.  I'm very happy to accept pull requests, suggestions, or other issues.
Enjoy!

Developing
----------

Run tests::

    $ make test

Or to set the tests running on every file change:

    $ make autotest

(requires ``entr``) 

BEWARE
------

I've done the best I can with this library - but there's no warrenty, no guarentee, nada.  A lot of
very clever people think the whole idea of trying to sandbox CPython is impossible.  Read the code
yourself, and use it at your own risk.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/danthedeckie/simpleeval",
    "name": "simpleeval",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "eval,simple,expression,parse,ast",
    "author": "Daniel Fairhead",
    "author_email": "danthedeckie@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/bc/9f/4b77fc4b6b988fc8e60a2f09f97e31c7aa2a02152ad22566726656d584da/simpleeval-0.9.12.tar.gz",
    "platform": "",
    "description": "simpleeval (Simple Eval)\n========================\n\n.. image:: https://github.com/danthedeckie/simpleeval/actions/workflows/ci.yml/badge.svg?branch=gh-actions-build\n   :target: https://github.com/danthedeckie/simpleeval/actions/\n   :alt: Build Status\n\n.. image:: https://codecov.io/gh/danthedeckie/simpleeval/branch/master/graph/badge.svg?token=isRnN1yrca\n   :target: https://codecov.io/gh/danthedeckie/simpleeval\n   :alt: Code Coverage\n\n.. image:: https://badge.fury.io/py/simpleeval.svg\n   :target: https://badge.fury.io/py/simpleeval\n   :alt: PyPI Version\n\nA quick single file library for easily adding evaluatable expressions into\npython projects.  Say you want to allow a user to set an alarm volume, which\ncould depend on the time of day, alarm level, how many previous alarms had gone\noff, and if there is music playing at the time.\n\nOr if you want to allow simple formulae in a web application, but don't want to\ngive full eval() access, or don't want to run in javascript on the client side.\n\nIt's deliberately very simple, pull it in from PyPI (pip or easy_install), or\neven just a single file you can dump into a project.\n\nInternally, it's using the amazing python ``ast`` module to parse the\nexpression, which allows very fine control of what is and isn't allowed.  It\nshould be completely safe in terms of what operations can be performed by the\nexpression.\n\nThe only issue I know to be aware of is that you can create an expression which\ntakes a long time to evaluate, or which evaluating requires an awful lot of\nmemory, which leaves the potential for DOS attacks.  There is basic protection\nagainst this, and you can lock it down further if you desire. (see the\nOperators_ section below)\n\nYou should be aware of this when deploying in a public setting.\n\nThe defaults are pretty locked down and basic, and it's very easy to add\nwhatever extra specific functionality you need (your own functions,\nvariable/name lookup, etc).\n\nBasic Usage\n-----------\n\nTo get very simple evaluating:\n\n.. code-block:: python\n\n    from simpleeval import simple_eval\n\n    simple_eval(\"21 + 21\")\n\nreturns ``42``.\n\nExpressions can be as complex and convoluted as you want:\n\n.. code-block:: python\n\n    simple_eval(\"21 + 19 / 7 + (8 % 3) ** 9\")\n\nreturns ``535.714285714``.\n\nYou can add your own functions in as well.\n\n.. code-block:: python\n\n    simple_eval(\"square(11)\", functions={\"square\": lambda x: x*x})\n\nreturns ``121``.\n\nFor more details of working with functions, read further down.\n\nNote:\n~~~~~\nall further examples use ``>>>`` to designate python code, as if you are using\nthe python interactive prompt.\n\n.. _Operators:\n\nOperators\n---------\nYou can add operators yourself, using the ``operators`` argument, but these are\nthe defaults:\n\n+--------+------------------------------------+\n|  ``+`` | add two things. ``x + y``          |\n|        | ``1 + 1`` -> ``2``                 |\n+--------+------------------------------------+\n|  ``-`` | subtract two things ``x - y``      |\n|        | ``100 - 1`` -> ``99``              |\n+--------+------------------------------------+\n|  ``/`` | divide one thing by another        |\n|        | ``x / y``                          |\n|        | ``100/10`` -> ``10``               |\n+--------+------------------------------------+\n|  ``*`` | multiple one thing by another      |\n|        | ``x * y``                          |\n|        | ``10 * 10`` -> ``100``             |\n+--------+------------------------------------+\n| ``**`` | 'to the power of' ``x**y``         |\n|        | ``2 ** 10`` -> ``1024``            |\n+--------+------------------------------------+\n| ``%``  | modulus. (remainder)  ``x % y``    |\n|        | ``15 % 4`` -> ``3``                |\n+--------+------------------------------------+\n| ``==`` | equals  ``x == y``                 |\n|        | ``15 == 4`` -> ``False``           |\n+--------+------------------------------------+\n| ``<``  | Less than. ``x < y``               |\n|        | ``1 < 4`` -> ``True``              |\n+--------+------------------------------------+\n| ``>``  | Greater than. ``x > y``            |\n|        | ``1 > 4`` -> ``False``             |\n+--------+------------------------------------+\n| ``<=`` | Less than or Equal to. ``x <= y``  |\n|        | ``1 < 4`` -> ``True``              |\n+--------+------------------------------------+\n| ``>=`` | Greater or Equal to ``x >= 21``    |\n|        | ``1 >= 4`` -> ``False``            |\n+--------+------------------------------------+\n| ``>>`` | \"Right shift\" the number.          |\n|        | ``100 >> 2`` -> ``25``             |\n+--------+------------------------------------+\n| ``<<`` | \"Left shift\" the number.           |\n|        | ``100 << 2`` -> ``400``            |\n+--------+------------------------------------+\n| ``in`` | is something contained within      |\n|        | something else.                    |\n|        | ``\"spam\" in \"my breakfast\"``       |\n|        | -> ``False``                       |\n+--------+------------------------------------+\n\n\nThe ``^`` operator is notably missing - not because it's hard, but because it\nis often mistaken for a exponent operator, not the bitwise operation that it is\nin python.  It's trivial to add back in again if you wish (using the class\nbased evaluator explained below):\n\n.. code-block:: python\n\n    >>> import ast\n    >>> import operator\n\n    >>> s = SimpleEval()\n    >>> s.operators[ast.BitXor] = operator.xor\n\n    >>> s.eval(\"2 ^ 10\")\n    8\n\nLimited Power\n~~~~~~~~~~~~~\n\nAlso note, the ``**`` operator has been locked down by default to have a\nmaximum input value of ``4000000``, which makes it somewhat harder to make\nexpressions which go on for ever.  You can change this limit by changing the\n``simpleeval.POWER_MAX`` module level value to whatever is an appropriate value\nfor you (and the hardware that you're running on) or if you want to completely\nremove all limitations, you can set the ``s.operators[ast.Pow] = operator.pow``\nor make your own function.\n\nOn my computer, ``9**9**5`` evaluates almost instantly, but ``9**9**6`` takes\nover 30 seconds.  Since ``9**7`` is ``4782969``, and so over the ``POWER_MAX``\nlimit, it throws a ``NumberTooHigh`` exception for you. (Otherwise it would go\non for hours, or until the computer runs out of memory)\n\nStrings (and other Iterables) Safety\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThere are also limits on string length (100000 characters,\n``MAX_STRING_LENGTH``).  This can be changed if you wish.\n\nRelated to this, if you try to create a silly long string/bytes/list, by doing\n``'i want to break free'.split() * 9999999999`` for instance, it will block you.\n\nIf Expressions\n--------------\n\nYou can use python style ``if x then y else z`` type expressions:\n\n.. code-block:: python\n\n    >>> simple_eval(\"'equal' if x == y else 'not equal'\",\n                    names={\"x\": 1, \"y\": 2})\n    'not equal'\n\nwhich, of course, can be nested:\n\n.. code-block:: python\n\n    >>> simple_eval(\"'a' if 1 == 2 else 'b' if 2 == 3 else 'c'\")\n    'c'\n\n\nFunctions\n---------\n\nYou can define functions which you'd like the expresssions to have access to:\n\n.. code-block:: python\n\n    >>> simple_eval(\"double(21)\", functions={\"double\": lambda x:x*2})\n    42\n\nYou can define \"real\" functions to pass in rather than lambdas, of course too,\nand even re-name them so that expressions can be shorter\n\n.. code-block:: python\n\n    >>> def double(x):\n            return x * 2\n    >>> simple_eval(\"d(100) + double(1)\", functions={\"d\": double, \"double\":double})\n    202\n\nIf you don't provide your own ``functions`` dict, then the the following defaults\nare provided in the ``DEFAULT_FUNCTIONS`` dict:\n\n+----------------+--------------------------------------------------+\n| ``randint(x)`` | Return a random ``int`` below ``x``              |\n+----------------+--------------------------------------------------+\n| ``rand()``     | Return a random ``float`` between 0 and 1        |\n+----------------+--------------------------------------------------+\n| ``int(x)``     | Convert ``x`` to an ``int``.                     |\n+----------------+--------------------------------------------------+\n| ``float(x)``   | Convert ``x`` to a ``float``.                    |\n+----------------+--------------------------------------------------+\n| ``str(x)``     | Convert ``x`` to a ``str`` (``unicode`` in py2)  |\n+----------------+--------------------------------------------------+\n\nIf you want to provide a list of functions, but want to keep these as well,\nthen you can do a normal python ``.copy()`` & ``.update``:\n\n.. code-block:: python\n\n    >>> my_functions = simpleeval.DEFAULT_FUNCTIONS.copy()\n    >>> my_functions.update(\n            square=(lambda x:x*x),\n            double=(lambda x:x+x),\n        )\n    >>> simple_eval('square(randint(100))', functions=my_functions)\n\nNames\n-----\n\nSometimes it's useful to have variables available, which in python terminology\nare called 'names'.\n\n.. code-block:: python\n\n    >>> simple_eval(\"a + b\", names={\"a\": 11, \"b\": 100})\n    111\n\nYou can also hand the handling of names over to a function, if you prefer:\n\n\n.. code-block:: python\n\n    >>> def name_handler(node):\n            return ord(node.id[0].lower(a))-96\n\n    >>> simple_eval('a + b', names=name_handler)\n    3\n\nThat was a bit of a silly example, but you could use this for pulling values\nfrom a database or file, say, or doing some kind of caching system.\n\nThe 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).\n\nCreating an Evaluator Class\n---------------------------\n\nRather than creating a new evaluator each time, if you are doing a lot of\nevaluations, you can create a SimpleEval object, and pass it expressions each\ntime (which should be a bit quicker, and certainly more convenient for some use\ncases):\n\n.. code-block:: python\n\n    >>> s = SimpleEval()\n\n    >>> s.eval(\"1 + 1\")\n    2\n\n    >>> s.eval('100 * 10')\n    1000\n\n    # and so on...\n\nYou can assign / edit the various options of the ``SimpleEval`` object if you\nwant to.  Either assign them during creation (like the ``simple_eval``\nfunction)\n\n.. code-block:: python\n\n    def boo():\n        return 'Boo!'\n\n    s = SimpleEval(functions={\"boo\": boo})\n\nor edit them after creation:\n\n.. code-block:: python\n\n    s.names['fortytwo'] = 42\n\nthis actually means you can modify names (or functions) with functions, if you\nreally feel so inclined:\n\n.. code-block:: python\n\n    s = SimpleEval()\n    def set_val(name, value):\n        s.names[name.value] = value.value\n        return value.value\n\n    s.functions = {'set': set_val}\n\n    s.eval(\"set('age', 111)\")\n\nSay.  This would allow a certain level of 'scriptyness' if you had these\nevaluations happening as callbacks in a program.  Although you really are\nreaching the end of what this library is intended for at this stage.\n\nCompound Types\n--------------\n\nCompound types (``dict``, ``tuple``, ``list``, ``set``) in general just work if\nyou pass them in as named objects.  If you want to allow creation of these, the\n``EvalWithCompoundTypes`` class works.  Just replace any use of ``SimpleEval`` with\nthat.\n\nThe ``EvalWithCompoundTypes`` class also contains support for simple comprehensions.\neg: ``[x + 1 for x in [1,2,3]]``.  There's a safety `MAX_COMPREHENSION_LENGTH` to control\nhow many items it'll allow before bailing too.  This also takes into account nested\ncomprehensions.\n\nSince the primary intention of this library is short expressions - an extra 'sweetener' is\nenabled by default.  You can access a dict (or similar's) keys using the .attr syntax:\n\n.. code-block:: python\n\n    >>>  simple_eval(\"foo.bar\", names={\"foo\": {\"bar\": 42}})\n    42\n\nfor instance.  You can turn this off either by setting the module global `ATTR_INDEX_FALLBACK`\nto `False`, or on the ``SimpleEval`` instance itself. e.g. ``evaller.ATTR_INDEX_FALLBACK=False``.\n\nExtending\n---------\n\nThe ``SimpleEval`` class is pretty easy to extend.  For instance, to create a\nversion that disallows method invocation on objects:\n\n.. code-block:: python\n\n    import ast\n    import simpleeval\n\n    class EvalNoMethods(simpleeval.SimpleEval):\n        def _eval_call(self, node):\n            if isinstance(node.func, ast.Attribute):\n                raise simpleeval.FeatureNotAvailable(\"No methods please, we're British\")\n            return super(EvalNoMethods, self)._eval_call(node)\n\nand then use ``EvalNoMethods`` instead of the ``SimpleEval`` class.\n\nOther...\n--------\n\nThe library supports python 3 - but should be mostly compatible (and tested before 0.9.11)\nwith python 2.7 as well.\n\nObject attributes that start with ``_`` or ``func_`` are disallowed by default.\nIf you really need that (BE CAREFUL!), then modify the module global\n``simpleeval.DISALLOW_PREFIXES``.\n\nA few builtin functions are listed in ``simpleeval.DISALLOW_FUNCTIONS``.  ``type``, ``open``, etc.\nIf you need to give access to this kind of functionality to your expressions, then be very\ncareful.  You'd be better wrapping the functions in your own safe wrappers.\n\nThe initial idea came from J.F. Sebastian on Stack Overflow\n( http://stackoverflow.com/a/9558001/1973500 ) with modifications and many improvements,\nsee the head of the main file for contributors list.\n\nPlease read the ``test_simpleeval.py`` file for other potential gotchas or\ndetails.  I'm very happy to accept pull requests, suggestions, or other issues.\nEnjoy!\n\nDeveloping\n----------\n\nRun tests::\n\n    $ make test\n\nOr to set the tests running on every file change:\n\n    $ make autotest\n\n(requires ``entr``) \n\nBEWARE\n------\n\nI've done the best I can with this library - but there's no warrenty, no guarentee, nada.  A lot of\nvery clever people think the whole idea of trying to sandbox CPython is impossible.  Read the code\nyourself, and use it at your own risk.\n\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "A simple, safe single expression evaluator library.",
    "version": "0.9.12",
    "split_keywords": [
        "eval",
        "simple",
        "expression",
        "parse",
        "ast"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "638d49210e359f916bb8ae4b347d780d",
                "sha256": "d82faa7dc88379614ea3b385fd84cc24f0aa4853432e267718526e5aeac6b1b9"
            },
            "downloads": -1,
            "filename": "simpleeval-0.9.12-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "638d49210e359f916bb8ae4b347d780d",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 14301,
            "upload_time": "2022-01-15T17:32:53",
            "upload_time_iso_8601": "2022-01-15T17:32:53.410420Z",
            "url": "https://files.pythonhosted.org/packages/7d/39/d5be0242308735b87bea7dc8fdadaca1056d4e73a3e7db6c5f0d20a90f7f/simpleeval-0.9.12-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "md5": "e96cf00b108e79eb2be1b2587d3a9217",
                "sha256": "3e0be507486d4e21cf9d08847c7e57dd61a1603950399985f7c5a0be7fd33e36"
            },
            "downloads": -1,
            "filename": "simpleeval-0.9.12.tar.gz",
            "has_sig": false,
            "md5_digest": "e96cf00b108e79eb2be1b2587d3a9217",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 22693,
            "upload_time": "2022-01-15T17:32:55",
            "upload_time_iso_8601": "2022-01-15T17:32:55.155285Z",
            "url": "https://files.pythonhosted.org/packages/bc/9f/4b77fc4b6b988fc8e60a2f09f97e31c7aa2a02152ad22566726656d584da/simpleeval-0.9.12.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-01-15 17:32:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "danthedeckie",
    "github_project": "simpleeval",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "simpleeval"
}
        
Elapsed time: 0.01315s