simpleeval 1.0.6__tar.gz → 1.0.7__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {simpleeval-1.0.6 → simpleeval-1.0.7}/PKG-INFO +1 -1
- {simpleeval-1.0.6 → simpleeval-1.0.7}/pyproject.toml +1 -1
- {simpleeval-1.0.6 → simpleeval-1.0.7}/simpleeval.py +12 -10
- simpleeval-1.0.6/.v2/lib/python3.13/site-packages/docutils/parsers/rst/include/README.rst +0 -17
- simpleeval-1.0.6/.v2/lib/python3.13/site-packages/docutils/writers/s5_html/themes/README.rst +0 -6
- simpleeval-1.0.6/.v2/lib/python3.13/site-packages/pip/_vendor/README.rst +0 -180
- simpleeval-1.0.6/.v314/lib/python3.14/site-packages/simpleeval-1.0.3.dist-info/licenses/LICENCE +0 -21
- simpleeval-1.0.6/.v314/lib/python3.14/site-packages/simpleeval.py +0 -768
- {simpleeval-1.0.6 → simpleeval-1.0.7}/.gitignore +0 -0
- {simpleeval-1.0.6 → simpleeval-1.0.7}/LICENCE +0 -0
- {simpleeval-1.0.6 → simpleeval-1.0.7}/README.rst +0 -0
- {simpleeval-1.0.6 → simpleeval-1.0.7}/test_simpleeval.py +0 -0
|
@@ -59,7 +59,8 @@ Contributors:
|
|
|
59
59
|
- smurfix (Matthias Urlichs) Allow clearing functions / operators / etc completely
|
|
60
60
|
- koenigsley (Mikhail Yeremeyev) documentation typos correction.
|
|
61
61
|
- kurtmckee (Kurt McKee) Infrastructure updates
|
|
62
|
-
- edgarrmondragon (Edgar Ramírez-Mondragón) Address Python 3.12+ deprecation warnings
|
|
62
|
+
- edgarrmondragon (Edgar Ramírez-Mondragón) Address Python 3.12+ deprecation warnings,
|
|
63
|
+
performance fixes
|
|
63
64
|
- cedk (Cédric Krier) <ced@b2ck.com> Allow running tests with Werror
|
|
64
65
|
- decorator-factory <decorator-factory@protonmail.com> More security fixes
|
|
65
66
|
- lkruitwagen (Lucas Kruitwagen) Adding support for dict comprehensions
|
|
@@ -135,12 +136,9 @@ DISALLOW_METHODS = [
|
|
|
135
136
|
########################################
|
|
136
137
|
# Tiny helpers:
|
|
137
138
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
return hash(value)
|
|
142
|
-
except TypeError:
|
|
143
|
-
return False
|
|
139
|
+
# Primitive types that are always safe: can't be modules, can't be in DISALLOW_FUNCTIONS,
|
|
140
|
+
# and don't need recursive container checks. Used as a fast path in _check_disallowed_items.
|
|
141
|
+
_PRIMITIVE_TYPES = frozenset({int, float, str, bool, type(None), bytes, complex})
|
|
144
142
|
|
|
145
143
|
|
|
146
144
|
# Disallow functions:
|
|
@@ -628,14 +626,16 @@ class SimpleEval(object): # pylint: disable=too-few-public-methods
|
|
|
628
626
|
Raises FeatureNotAvailable if forbidden content found.
|
|
629
627
|
ModuleWrapper instances are allowed (explicit opt-in to module access).
|
|
630
628
|
"""
|
|
629
|
+
# Fast path: primitive scalars are always safe (most common case)
|
|
630
|
+
if type(item) in _PRIMITIVE_TYPES:
|
|
631
|
+
return
|
|
632
|
+
|
|
631
633
|
# Allow ModuleWrapper (explicit opt-in to module access)
|
|
632
634
|
if isinstance(item, ModuleWrapper):
|
|
633
635
|
return
|
|
634
636
|
|
|
635
637
|
if isinstance(item, types.ModuleType):
|
|
636
638
|
raise FeatureNotAvailable("Sorry, modules are not allowed")
|
|
637
|
-
if is_hashable(item) and item in DISALLOW_FUNCTIONS:
|
|
638
|
-
raise FeatureNotAvailable("This function is forbidden")
|
|
639
639
|
|
|
640
640
|
if isinstance(item, (list, tuple)):
|
|
641
641
|
for element in item:
|
|
@@ -643,6 +643,8 @@ class SimpleEval(object): # pylint: disable=too-few-public-methods
|
|
|
643
643
|
elif isinstance(item, dict):
|
|
644
644
|
for value in item.values():
|
|
645
645
|
self._check_disallowed_items(value)
|
|
646
|
+
elif callable(item) and item in DISALLOW_FUNCTIONS:
|
|
647
|
+
raise FeatureNotAvailable("This function is forbidden")
|
|
646
648
|
|
|
647
649
|
@staticmethod
|
|
648
650
|
def parse(expr):
|
|
@@ -875,7 +877,7 @@ class SimpleEval(object): # pylint: disable=too-few-public-methods
|
|
|
875
877
|
if item is not _ATTR_NOT_FOUND:
|
|
876
878
|
if isinstance(item, types.ModuleType):
|
|
877
879
|
raise FeatureNotAvailable("Sorry, modules are not allowed in attribute access")
|
|
878
|
-
if
|
|
880
|
+
if callable(item) and item in DISALLOW_FUNCTIONS:
|
|
879
881
|
raise FeatureNotAvailable("This function is forbidden")
|
|
880
882
|
return item
|
|
881
883
|
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
============================================
|
|
2
|
-
``docutils/parsers/rst/include`` Directory
|
|
3
|
-
============================================
|
|
4
|
-
|
|
5
|
-
This directory contains standard data files intended for inclusion in
|
|
6
|
-
reStructuredText documents. To access these files, use the "include"
|
|
7
|
-
directive with the special syntax for standard "include" data files,
|
|
8
|
-
angle brackets around the file name::
|
|
9
|
-
|
|
10
|
-
.. include:: <isonum.txt>
|
|
11
|
-
|
|
12
|
-
See the documentation for the `"include" directive`__ and
|
|
13
|
-
`reStructuredText Standard Definition Files`__ for
|
|
14
|
-
details.
|
|
15
|
-
|
|
16
|
-
__ https://docutils.sourceforge.io/docs/ref/rst/directives.html#include
|
|
17
|
-
__ https://docutils.sourceforge.io/docs/ref/rst/definitions.html
|
simpleeval-1.0.6/.v2/lib/python3.13/site-packages/docutils/writers/s5_html/themes/README.rst
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
Except where otherwise noted, all files in this
|
|
2
|
-
directory have been released into the Public Domain.
|
|
3
|
-
|
|
4
|
-
These files are based on files from S5 1.1, released into the Public
|
|
5
|
-
Domain by Eric Meyer. For further details, please see
|
|
6
|
-
http://www.meyerweb.com/eric/tools/s5/credits.html.
|
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
================
|
|
2
|
-
Vendoring Policy
|
|
3
|
-
================
|
|
4
|
-
|
|
5
|
-
* Vendored libraries **MUST** not be modified except as required to
|
|
6
|
-
successfully vendor them.
|
|
7
|
-
* Vendored libraries **MUST** be released copies of libraries available on
|
|
8
|
-
PyPI.
|
|
9
|
-
* Vendored libraries **MUST** be available under a license that allows
|
|
10
|
-
them to be integrated into ``pip``, which is released under the MIT license.
|
|
11
|
-
* Vendored libraries **MUST** be accompanied with LICENSE files.
|
|
12
|
-
* The versions of libraries vendored in pip **MUST** be reflected in
|
|
13
|
-
``pip/_vendor/vendor.txt``.
|
|
14
|
-
* Vendored libraries **MUST** function without any build steps such as ``2to3``
|
|
15
|
-
or compilation of C code, practically this limits to single source 2.x/3.x and
|
|
16
|
-
pure Python.
|
|
17
|
-
* Any modifications made to libraries **MUST** be noted in
|
|
18
|
-
``pip/_vendor/README.rst`` and their corresponding patches **MUST** be
|
|
19
|
-
included ``tools/vendoring/patches``.
|
|
20
|
-
* Vendored libraries should have corresponding ``vendored()`` entries in
|
|
21
|
-
``pip/_vendor/__init__.py``.
|
|
22
|
-
|
|
23
|
-
Rationale
|
|
24
|
-
=========
|
|
25
|
-
|
|
26
|
-
Historically pip has not had any dependencies except for ``setuptools`` itself,
|
|
27
|
-
choosing instead to implement any functionality it needed to prevent needing
|
|
28
|
-
a dependency. However, starting with pip 1.5, we began to replace code that was
|
|
29
|
-
implemented inside of pip with reusable libraries from PyPI. This brought the
|
|
30
|
-
typical benefits of reusing libraries instead of reinventing the wheel like
|
|
31
|
-
higher quality and more battle tested code, centralization of bug fixes
|
|
32
|
-
(particularly security sensitive ones), and better/more features for less work.
|
|
33
|
-
|
|
34
|
-
However, there are several issues with having dependencies in the traditional
|
|
35
|
-
way (via ``install_requires``) for pip. These issues are:
|
|
36
|
-
|
|
37
|
-
**Fragility**
|
|
38
|
-
When pip depends on another library to function then if for whatever reason
|
|
39
|
-
that library either isn't installed or an incompatible version is installed
|
|
40
|
-
then pip ceases to function. This is of course true for all Python
|
|
41
|
-
applications, however for every application *except* for pip the way you fix
|
|
42
|
-
it is by re-running pip. Obviously, when pip can't run, you can't use pip to
|
|
43
|
-
fix pip, so you're left having to manually resolve dependencies and
|
|
44
|
-
installing them by hand.
|
|
45
|
-
|
|
46
|
-
**Making other libraries uninstallable**
|
|
47
|
-
One of pip's current dependencies is the ``requests`` library, for which pip
|
|
48
|
-
requires a fairly recent version to run. If pip depended on ``requests`` in
|
|
49
|
-
the traditional manner, then we'd either have to maintain compatibility with
|
|
50
|
-
every ``requests`` version that has ever existed (and ever will), OR allow
|
|
51
|
-
pip to render certain versions of ``requests`` uninstallable. (The second
|
|
52
|
-
issue, although technically true for any Python application, is magnified by
|
|
53
|
-
pip's ubiquity; pip is installed by default in Python, in ``pyvenv``, and in
|
|
54
|
-
``virtualenv``.)
|
|
55
|
-
|
|
56
|
-
**Security**
|
|
57
|
-
This might seem puzzling at first glance, since vendoring has a tendency to
|
|
58
|
-
complicate updating dependencies for security updates, and that holds true
|
|
59
|
-
for pip. However, given the *other* reasons for avoiding dependencies, the
|
|
60
|
-
alternative is for pip to reinvent the wheel itself. This is what pip did
|
|
61
|
-
historically. It forced pip to re-implement its own HTTPS verification
|
|
62
|
-
routines as a workaround for the Python standard library's lack of SSL
|
|
63
|
-
validation, which resulted in similar bugs in the validation routine in
|
|
64
|
-
``requests`` and ``urllib3``, except that they had to be discovered and
|
|
65
|
-
fixed independently. Even though we're vendoring, reusing libraries keeps
|
|
66
|
-
pip more secure by relying on the great work of our dependencies, *and*
|
|
67
|
-
allowing for faster, easier security fixes by simply pulling in newer
|
|
68
|
-
versions of dependencies.
|
|
69
|
-
|
|
70
|
-
**Bootstrapping**
|
|
71
|
-
Currently most popular methods of installing pip rely on pip's
|
|
72
|
-
self-contained nature to install pip itself. These tools work by bundling a
|
|
73
|
-
copy of pip, adding it to ``sys.path``, and then executing that copy of pip.
|
|
74
|
-
This is done instead of implementing a "mini installer" (to reduce
|
|
75
|
-
duplication); pip already knows how to install a Python package, and is far
|
|
76
|
-
more battle-tested than any "mini installer" could ever possibly be.
|
|
77
|
-
|
|
78
|
-
Many downstream redistributors have policies against this kind of bundling, and
|
|
79
|
-
instead opt to patch the software they distribute to debundle it and make it
|
|
80
|
-
rely on the global versions of the software that they already have packaged
|
|
81
|
-
(which may have its own patches applied to it). We (the pip team) would prefer
|
|
82
|
-
it if pip was *not* debundled in this manner due to the above reasons and
|
|
83
|
-
instead we would prefer it if pip would be left intact as it is now.
|
|
84
|
-
|
|
85
|
-
In the longer term, if someone has a *portable* solution to the above problems,
|
|
86
|
-
other than the bundling method we currently use, that doesn't add additional
|
|
87
|
-
problems that are unreasonable then we would be happy to consider, and possibly
|
|
88
|
-
switch to said method. This solution must function correctly across all of the
|
|
89
|
-
situation that we expect pip to be used and not mandate some external mechanism
|
|
90
|
-
such as OS packages.
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
Modifications
|
|
94
|
-
=============
|
|
95
|
-
|
|
96
|
-
* ``setuptools`` is completely stripped to only keep ``pkg_resources``.
|
|
97
|
-
* ``pkg_resources`` has been modified to import its dependencies from
|
|
98
|
-
``pip._vendor``, and to use the vendored copy of ``platformdirs``
|
|
99
|
-
rather than ``appdirs``.
|
|
100
|
-
* ``packaging`` has been modified to import its dependencies from
|
|
101
|
-
``pip._vendor``.
|
|
102
|
-
* ``CacheControl`` has been modified to import its dependencies from
|
|
103
|
-
``pip._vendor``.
|
|
104
|
-
* ``requests`` has been modified to import its other dependencies from
|
|
105
|
-
``pip._vendor`` and to *not* load ``simplejson`` (all platforms) and
|
|
106
|
-
``pyopenssl`` (Windows).
|
|
107
|
-
* ``platformdirs`` has been modified to import its submodules from ``pip._vendor.platformdirs``.
|
|
108
|
-
|
|
109
|
-
Automatic Vendoring
|
|
110
|
-
===================
|
|
111
|
-
|
|
112
|
-
Vendoring is automated via the `vendoring <https://pypi.org/project/vendoring/>`_ tool from the content of
|
|
113
|
-
``pip/_vendor/vendor.txt`` and the different patches in
|
|
114
|
-
``tools/vendoring/patches``.
|
|
115
|
-
Launch it via ``vendoring sync . -v`` (requires ``vendoring>=0.2.2``).
|
|
116
|
-
Tool configuration is done via ``pyproject.toml``.
|
|
117
|
-
|
|
118
|
-
To update the vendored library versions, we have a session defined in ``nox``.
|
|
119
|
-
The command to upgrade everything is::
|
|
120
|
-
|
|
121
|
-
nox -s vendoring -- --upgrade-all --skip urllib3 --skip setuptools
|
|
122
|
-
|
|
123
|
-
At the time of writing (April 2025) we do not upgrade ``urllib3`` because the
|
|
124
|
-
next version is a major upgrade and will be handled as an independent PR. We also
|
|
125
|
-
do not upgrade ``setuptools``, because we only rely on ``pkg_resources``, and
|
|
126
|
-
tracking every ``setuptools`` change is unnecessary for our needs.
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
Managing Local Patches
|
|
130
|
-
======================
|
|
131
|
-
|
|
132
|
-
The ``vendoring`` tool automatically applies our local patches, but updating,
|
|
133
|
-
the patches sometimes no longer apply cleanly. In that case, the update will
|
|
134
|
-
fail. To resolve this, take the following steps:
|
|
135
|
-
|
|
136
|
-
1. Revert any incomplete changes in the revendoring branch, to ensure you have
|
|
137
|
-
a clean starting point.
|
|
138
|
-
2. Run the revendoring of the library with a problem again: ``nox -s vendoring
|
|
139
|
-
-- --upgrade <library_name>``.
|
|
140
|
-
3. This will fail again, but you will have the original source in your working
|
|
141
|
-
directory. Review the existing patch against the source, and modify the patch
|
|
142
|
-
to reflect the new version of the source. If you ``git add`` the changes the
|
|
143
|
-
vendoring made, you can modify the source to reflect the patch file and then
|
|
144
|
-
generate a new patch with ``git diff``.
|
|
145
|
-
4. Now, revert everything *except* the patch file changes. Leave the modified
|
|
146
|
-
patch file unstaged but saved in the working tree.
|
|
147
|
-
5. Re-run the vendoring. This time, it should pick up the changed patch file
|
|
148
|
-
and apply it cleanly. The patch file changes will be committed along with the
|
|
149
|
-
revendoring, so the new commit should be ready to test and publish as a PR.
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
Debundling
|
|
153
|
-
==========
|
|
154
|
-
|
|
155
|
-
As mentioned in the rationale, we, the pip team, would prefer it if pip was not
|
|
156
|
-
debundled (other than optionally ``pip/_vendor/requests/cacert.pem``) and that
|
|
157
|
-
pip was left intact. However, if you insist on doing so, we have a
|
|
158
|
-
semi-supported method (that we don't test in our CI) and requires a bit of
|
|
159
|
-
extra work on your end in order to solve the problems described above.
|
|
160
|
-
|
|
161
|
-
1. Delete everything in ``pip/_vendor/`` **except** for
|
|
162
|
-
``pip/_vendor/__init__.py`` and ``pip/_vendor/vendor.txt``.
|
|
163
|
-
2. Generate wheels for each of pip's dependencies (and any of their
|
|
164
|
-
dependencies) using your patched copies of these libraries. These must be
|
|
165
|
-
placed somewhere on the filesystem that pip can access (``pip/_vendor`` is
|
|
166
|
-
the default assumption).
|
|
167
|
-
3. Modify ``pip/_vendor/__init__.py`` so that the ``DEBUNDLED`` variable is
|
|
168
|
-
``True``.
|
|
169
|
-
4. Upon installation, the ``INSTALLER`` file in pip's own ``dist-info``
|
|
170
|
-
directory should be set to something other than ``pip``, so that pip
|
|
171
|
-
can detect that it wasn't installed using itself.
|
|
172
|
-
5. *(optional)* If you've placed the wheels in a location other than
|
|
173
|
-
``pip/_vendor/``, then modify ``pip/_vendor/__init__.py`` so that the
|
|
174
|
-
``WHEEL_DIR`` variable points to the location you've placed them.
|
|
175
|
-
6. *(optional)* Update the ``pip_self_version_check`` logic to use the
|
|
176
|
-
appropriate logic for determining the latest available version of pip and
|
|
177
|
-
prompt the user with the correct upgrade message.
|
|
178
|
-
|
|
179
|
-
Note that partial debundling is **NOT** supported. You need to prepare wheels
|
|
180
|
-
for all dependencies for successful debundling.
|
simpleeval-1.0.6/.v314/lib/python3.14/site-packages/simpleeval-1.0.3.dist-info/licenses/LICENCE
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
simpleeval - Copyright (c) 2013-2024 Daniel Fairhead
|
|
2
|
-
|
|
3
|
-
(MIT Licence)
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in
|
|
13
|
-
all copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
21
|
-
THE SOFTWARE.
|
|
@@ -1,768 +0,0 @@
|
|
|
1
|
-
"""
|
|
2
|
-
SimpleEval - (C) 2013-2024 Daniel Fairhead
|
|
3
|
-
-------------------------------------
|
|
4
|
-
|
|
5
|
-
An short, easy to use, safe and reasonably extensible expression evaluator.
|
|
6
|
-
Designed for things like in a website where you want to allow the user to
|
|
7
|
-
generate a string, or a number from some other input, without allowing full
|
|
8
|
-
eval() or other unsafe or needlessly complex linguistics.
|
|
9
|
-
|
|
10
|
-
-------------------------------------
|
|
11
|
-
|
|
12
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
-
in the Software without restriction, including without limitation the rights
|
|
15
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
-
furnished to do so, subject to the following conditions:
|
|
18
|
-
|
|
19
|
-
The above copyright notice and this permission notice shall be included in
|
|
20
|
-
all copies or substantial portions of the Software.
|
|
21
|
-
|
|
22
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
28
|
-
THE SOFTWARE.
|
|
29
|
-
|
|
30
|
-
-------------------------------------
|
|
31
|
-
|
|
32
|
-
Initial idea copied from J.F. Sebastian on Stack Overflow
|
|
33
|
-
( http://stackoverflow.com/a/9558001/1973500 ) with
|
|
34
|
-
modifications and many improvements.
|
|
35
|
-
|
|
36
|
-
-------------------------------------
|
|
37
|
-
Contributors:
|
|
38
|
-
- corro (Robin Baumgartner) (py3k)
|
|
39
|
-
- dratchkov (David R) (nested dicts)
|
|
40
|
-
- marky1991 (Mark Young) (slicing)
|
|
41
|
-
- T045T (Nils Berg) (!=, py3kstr, obj.
|
|
42
|
-
- perkinslr (Logan Perkins) (.__globals__ or .func_ breakouts)
|
|
43
|
-
- impala2 (Kirill Stepanov) (massive _eval refactor)
|
|
44
|
-
- gk (ugik) (Other iterables than str can DOS too, and can be made)
|
|
45
|
-
- daveisfera (Dave Johansen) 'not' Boolean op, Pycharm, pep8, various other fixes
|
|
46
|
-
- xaled (Khalid Grandi) method chaining correctly, double-eval bugfix.
|
|
47
|
-
- EdwardBetts (Edward Betts) spelling correction.
|
|
48
|
-
- charlax (Charles-Axel Dein charlax) Makefile and cleanups
|
|
49
|
-
- mommothazaz123 (Andrew Zhu) f"string" support, Python 3.8 support
|
|
50
|
-
- lubieowoce (Uryga) various potential vulnerabilities
|
|
51
|
-
- JCavallo (Jean Cavallo) names dict shouldn't be modified
|
|
52
|
-
- Birne94 (Daniel Birnstiel) for fixing leaking generators, star expressions
|
|
53
|
-
- patricksurry (Patrick Surry) or should return last value, even if falsy.
|
|
54
|
-
- shughes-uk (Samantha Hughes) python w/o 'site' should not fail to import.
|
|
55
|
-
- KOLANICH packaging / deployment / setup help & << + >> & other bit ops
|
|
56
|
-
- graingert (Thomas Grainger) packaging / deployment / setup help
|
|
57
|
-
- bozokopic (Bozo Kopic) Memory leak fix
|
|
58
|
-
- daxamin (Dax Amin) Better error for attempting to eval empty string
|
|
59
|
-
- smurfix (Matthias Urlichs) Allow clearing functions / operators / etc completely
|
|
60
|
-
- koenigsley (Mikhail Yeremeyev) documentation typos correction.
|
|
61
|
-
- kurtmckee (Kurt McKee) Infrastructure updates
|
|
62
|
-
- edgarrmondragon (Edgar Ramírez-Mondragón) Address Python 3.12+ deprecation warnings
|
|
63
|
-
- cedk (Cédric Krier) <ced@b2ck.com> Allow running tests with Werror
|
|
64
|
-
- decorator-factory <decorator-factory@protonmail.com> More security fixes
|
|
65
|
-
- lkruitwagen (Lucas Kruitwagen) Adding support for dict comprehensions
|
|
66
|
-
|
|
67
|
-
-------------------------------------
|
|
68
|
-
Basic Usage:
|
|
69
|
-
|
|
70
|
-
>>> s = SimpleEval()
|
|
71
|
-
>>> s.eval("20 + 30")
|
|
72
|
-
50
|
|
73
|
-
|
|
74
|
-
You can add your own functions easily too:
|
|
75
|
-
|
|
76
|
-
if file.txt contents is "11"
|
|
77
|
-
|
|
78
|
-
>>> def get_file():
|
|
79
|
-
... with open("file.txt", 'r') as f:
|
|
80
|
-
... return f.read()
|
|
81
|
-
|
|
82
|
-
>>> s.functions["get_file"] = get_file
|
|
83
|
-
>>> s.eval("int(get_file()) + 31")
|
|
84
|
-
42
|
|
85
|
-
|
|
86
|
-
For more information, see the full package documentation on pypi, or the github
|
|
87
|
-
repo.
|
|
88
|
-
|
|
89
|
-
-----------
|
|
90
|
-
|
|
91
|
-
If you don't need to re-use the evaluator (with it's names, functions, etc),
|
|
92
|
-
then you can use the simple_eval() function:
|
|
93
|
-
|
|
94
|
-
>>> simple_eval("21 + 19")
|
|
95
|
-
40
|
|
96
|
-
|
|
97
|
-
You can pass names, operators and functions to the simple_eval function as
|
|
98
|
-
well:
|
|
99
|
-
|
|
100
|
-
>>> simple_eval("40 + two", names={"two": 2})
|
|
101
|
-
42
|
|
102
|
-
|
|
103
|
-
"""
|
|
104
|
-
|
|
105
|
-
import ast
|
|
106
|
-
import operator as op
|
|
107
|
-
import sys
|
|
108
|
-
import warnings
|
|
109
|
-
from random import random
|
|
110
|
-
|
|
111
|
-
########################################
|
|
112
|
-
# Module wide 'globals'
|
|
113
|
-
|
|
114
|
-
MAX_STRING_LENGTH = 100000
|
|
115
|
-
MAX_COMPREHENSION_LENGTH = 10000
|
|
116
|
-
MAX_POWER = 4000000 # highest exponent
|
|
117
|
-
MAX_SHIFT = 10000 # highest << or >> (lshift / rshift)
|
|
118
|
-
MAX_SHIFT_BASE = int(sys.float_info.max) # highest on left side of << or >>
|
|
119
|
-
DISALLOW_PREFIXES = ["_", "func_"]
|
|
120
|
-
DISALLOW_METHODS = [
|
|
121
|
-
"format",
|
|
122
|
-
"format_map",
|
|
123
|
-
"mro",
|
|
124
|
-
"tb_frame",
|
|
125
|
-
"gi_frame",
|
|
126
|
-
"ag_frame",
|
|
127
|
-
"cr_frame",
|
|
128
|
-
"exec",
|
|
129
|
-
]
|
|
130
|
-
|
|
131
|
-
# Disallow functions:
|
|
132
|
-
# This, strictly speaking, is not necessary. These /should/ never be accessible anyway,
|
|
133
|
-
# if DISALLOW_PREFIXES and DISALLOW_METHODS are all right. This is here to try and help
|
|
134
|
-
# people not be stupid. Allowing these functions opens up all sorts of holes - if any of
|
|
135
|
-
# their functionality is required, then please wrap them up in a safe container. And think
|
|
136
|
-
# very hard about it first. And don't say I didn't warn you.
|
|
137
|
-
# builtins is a dict in python >3.6 but a module before
|
|
138
|
-
DISALLOW_FUNCTIONS = {type, isinstance, eval, getattr, setattr, repr, compile, open, exec}
|
|
139
|
-
if hasattr(__builtins__, "help") or (
|
|
140
|
-
hasattr(__builtins__, "__contains__") and "help" in __builtins__ # type: ignore
|
|
141
|
-
):
|
|
142
|
-
# PyInstaller environment doesn't include this module.
|
|
143
|
-
DISALLOW_FUNCTIONS.add(help)
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
########################################
|
|
147
|
-
# Exceptions:
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
class InvalidExpression(Exception):
|
|
151
|
-
"""Generic Exception"""
|
|
152
|
-
|
|
153
|
-
pass
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
class FunctionNotDefined(InvalidExpression):
|
|
157
|
-
"""sorry! That function isn't defined!"""
|
|
158
|
-
|
|
159
|
-
def __init__(self, func_name, expression):
|
|
160
|
-
self.message = "Function '{0}' not defined," " for expression '{1}'.".format(
|
|
161
|
-
func_name, expression
|
|
162
|
-
)
|
|
163
|
-
setattr(self, "func_name", func_name) # bypass 2to3 confusion.
|
|
164
|
-
self.expression = expression
|
|
165
|
-
|
|
166
|
-
super(InvalidExpression, self).__init__(self.message)
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
class NameNotDefined(InvalidExpression):
|
|
170
|
-
"""a name isn't defined."""
|
|
171
|
-
|
|
172
|
-
def __init__(self, name, expression):
|
|
173
|
-
self.name = name
|
|
174
|
-
self.message = "'{0}' is not defined for expression '{1}'".format(name, expression)
|
|
175
|
-
self.expression = expression
|
|
176
|
-
|
|
177
|
-
super(InvalidExpression, self).__init__(self.message)
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
class AttributeDoesNotExist(InvalidExpression):
|
|
181
|
-
"""attribute does not exist"""
|
|
182
|
-
|
|
183
|
-
def __init__(self, attr, expression):
|
|
184
|
-
self.message = "Attribute '{0}' does not exist in expression '{1}'".format(
|
|
185
|
-
attr, expression
|
|
186
|
-
)
|
|
187
|
-
self.attr = attr
|
|
188
|
-
self.expression = expression
|
|
189
|
-
|
|
190
|
-
super(InvalidExpression, self).__init__(self.message)
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
class OperatorNotDefined(InvalidExpression):
|
|
194
|
-
"""operator does not exist"""
|
|
195
|
-
|
|
196
|
-
def __init__(self, attr, expression):
|
|
197
|
-
self.message = "Operator '{0}' does not exist in expression '{1}'".format(attr, expression)
|
|
198
|
-
self.attr = attr
|
|
199
|
-
self.expression = expression
|
|
200
|
-
|
|
201
|
-
super(InvalidExpression, self).__init__(self.message)
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
class FeatureNotAvailable(InvalidExpression):
|
|
205
|
-
"""What you're trying to do is not allowed."""
|
|
206
|
-
|
|
207
|
-
pass
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
class NumberTooHigh(InvalidExpression):
|
|
211
|
-
"""Sorry! That number is too high. I don't want to spend the
|
|
212
|
-
next 10 years evaluating this expression!"""
|
|
213
|
-
|
|
214
|
-
pass
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
class IterableTooLong(InvalidExpression):
|
|
218
|
-
"""That iterable is **way** too long, baby."""
|
|
219
|
-
|
|
220
|
-
pass
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
class AssignmentAttempted(UserWarning):
|
|
224
|
-
"""Assignment not allowed in SimpleEval"""
|
|
225
|
-
|
|
226
|
-
pass
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
class MultipleExpressions(UserWarning):
|
|
230
|
-
"""Only the first expression parsed will be used"""
|
|
231
|
-
|
|
232
|
-
pass
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
########################################
|
|
236
|
-
# Default simple functions to include:
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
def random_int(top):
|
|
240
|
-
"""return a random int below <top>"""
|
|
241
|
-
|
|
242
|
-
return int(random() * top)
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
def safe_power(a, b): # pylint: disable=invalid-name
|
|
246
|
-
"""a limited exponent/to-the-power-of function, for safety reasons"""
|
|
247
|
-
|
|
248
|
-
if abs(a) > MAX_POWER or abs(b) > MAX_POWER:
|
|
249
|
-
raise NumberTooHigh("Sorry! I don't want to evaluate {0} ** {1}".format(a, b))
|
|
250
|
-
return a**b
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
def safe_mult(a, b): # pylint: disable=invalid-name
|
|
254
|
-
"""limit the number of times an iterable can be repeated..."""
|
|
255
|
-
|
|
256
|
-
if hasattr(a, "__len__") and b * len(a) > MAX_STRING_LENGTH:
|
|
257
|
-
raise IterableTooLong("Sorry, I will not evaluate something that long.")
|
|
258
|
-
if hasattr(b, "__len__") and a * len(b) > MAX_STRING_LENGTH:
|
|
259
|
-
raise IterableTooLong("Sorry, I will not evaluate something that long.")
|
|
260
|
-
|
|
261
|
-
return a * b
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
def safe_add(a, b): # pylint: disable=invalid-name
|
|
265
|
-
"""iterable length limit again"""
|
|
266
|
-
|
|
267
|
-
if hasattr(a, "__len__") and hasattr(b, "__len__"):
|
|
268
|
-
if len(a) + len(b) > MAX_STRING_LENGTH:
|
|
269
|
-
raise IterableTooLong(
|
|
270
|
-
"Sorry, adding those two together would" " make something too long."
|
|
271
|
-
)
|
|
272
|
-
return a + b
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
def safe_rshift(a, b): # pylint: disable=invalid-name
|
|
276
|
-
"""rshift, but with input limits"""
|
|
277
|
-
if abs(b) > MAX_SHIFT or abs(a) > MAX_SHIFT_BASE:
|
|
278
|
-
raise NumberTooHigh("Sorry! I don't want to evaluate {0} >> {1}".format(a, b))
|
|
279
|
-
return a >> b
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
def safe_lshift(a, b): # pylint: disable=invalid-name
|
|
283
|
-
"""lshift, but with input limits"""
|
|
284
|
-
if abs(b) > MAX_SHIFT or abs(a) > MAX_SHIFT_BASE:
|
|
285
|
-
raise NumberTooHigh("Sorry! I don't want to evaluate {0} << {1}".format(a, b))
|
|
286
|
-
return a << b
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
########################################
|
|
290
|
-
# Defaults for the evaluator:
|
|
291
|
-
|
|
292
|
-
DEFAULT_OPERATORS = {
|
|
293
|
-
ast.Add: safe_add,
|
|
294
|
-
ast.Sub: op.sub,
|
|
295
|
-
ast.Mult: safe_mult,
|
|
296
|
-
ast.Div: op.truediv,
|
|
297
|
-
ast.FloorDiv: op.floordiv,
|
|
298
|
-
ast.RShift: safe_rshift,
|
|
299
|
-
ast.LShift: safe_lshift,
|
|
300
|
-
ast.Pow: safe_power,
|
|
301
|
-
ast.Mod: op.mod,
|
|
302
|
-
ast.Eq: op.eq,
|
|
303
|
-
ast.NotEq: op.ne,
|
|
304
|
-
ast.Gt: op.gt,
|
|
305
|
-
ast.Lt: op.lt,
|
|
306
|
-
ast.GtE: op.ge,
|
|
307
|
-
ast.LtE: op.le,
|
|
308
|
-
ast.Not: op.not_,
|
|
309
|
-
ast.USub: op.neg,
|
|
310
|
-
ast.UAdd: op.pos,
|
|
311
|
-
ast.BitXor: op.xor,
|
|
312
|
-
ast.BitOr: op.or_,
|
|
313
|
-
ast.BitAnd: op.and_,
|
|
314
|
-
ast.Invert: op.invert,
|
|
315
|
-
ast.In: lambda x, y: op.contains(y, x),
|
|
316
|
-
ast.NotIn: lambda x, y: not op.contains(y, x),
|
|
317
|
-
ast.Is: lambda x, y: x is y,
|
|
318
|
-
ast.IsNot: lambda x, y: x is not y,
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
DEFAULT_FUNCTIONS = {
|
|
322
|
-
"rand": random,
|
|
323
|
-
"randint": random_int,
|
|
324
|
-
"int": int,
|
|
325
|
-
"float": float,
|
|
326
|
-
"str": str,
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
DEFAULT_NAMES = {"True": True, "False": False, "None": None}
|
|
330
|
-
|
|
331
|
-
ATTR_INDEX_FALLBACK = True
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
########################################
|
|
335
|
-
# And the actual evaluator:
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
class SimpleEval(object): # pylint: disable=too-few-public-methods
|
|
339
|
-
"""A very simple expression parser.
|
|
340
|
-
>>> s = SimpleEval()
|
|
341
|
-
>>> s.eval("20 + 30 - ( 10 * 5)")
|
|
342
|
-
0
|
|
343
|
-
"""
|
|
344
|
-
|
|
345
|
-
expr = ""
|
|
346
|
-
|
|
347
|
-
def __init__(self, operators=None, functions=None, names=None):
|
|
348
|
-
"""
|
|
349
|
-
Create the evaluator instance. Set up valid operators (+,-, etc)
|
|
350
|
-
functions (add, random, get_val, whatever) and names."""
|
|
351
|
-
|
|
352
|
-
if operators is None:
|
|
353
|
-
operators = DEFAULT_OPERATORS.copy()
|
|
354
|
-
if functions is None:
|
|
355
|
-
functions = DEFAULT_FUNCTIONS.copy()
|
|
356
|
-
if names is None:
|
|
357
|
-
names = DEFAULT_NAMES.copy()
|
|
358
|
-
|
|
359
|
-
self.operators = operators
|
|
360
|
-
self.functions = functions
|
|
361
|
-
self.names = names
|
|
362
|
-
|
|
363
|
-
self.nodes = {
|
|
364
|
-
ast.Expr: self._eval_expr,
|
|
365
|
-
ast.Assign: self._eval_assign,
|
|
366
|
-
ast.AugAssign: self._eval_aug_assign,
|
|
367
|
-
ast.Import: self._eval_import,
|
|
368
|
-
ast.Name: self._eval_name,
|
|
369
|
-
ast.UnaryOp: self._eval_unaryop,
|
|
370
|
-
ast.BinOp: self._eval_binop,
|
|
371
|
-
ast.BoolOp: self._eval_boolop,
|
|
372
|
-
ast.Compare: self._eval_compare,
|
|
373
|
-
ast.IfExp: self._eval_ifexp,
|
|
374
|
-
ast.Call: self._eval_call,
|
|
375
|
-
ast.keyword: self._eval_keyword,
|
|
376
|
-
ast.Subscript: self._eval_subscript,
|
|
377
|
-
ast.Attribute: self._eval_attribute,
|
|
378
|
-
ast.Index: self._eval_index,
|
|
379
|
-
ast.Slice: self._eval_slice,
|
|
380
|
-
ast.JoinedStr: self._eval_joinedstr,
|
|
381
|
-
ast.FormattedValue: self._eval_formattedvalue,
|
|
382
|
-
ast.Constant: self._eval_constant,
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
with warnings.catch_warnings():
|
|
386
|
-
warnings.simplefilter("ignore")
|
|
387
|
-
# py3.12 deprecated ast.Num, ast.Str, ast.NameConstant
|
|
388
|
-
# https://docs.python.org/3.12/whatsnew/3.12.html#deprecated
|
|
389
|
-
if Num := getattr(ast, "Num", None):
|
|
390
|
-
self.nodes[Num] = self._eval_num
|
|
391
|
-
|
|
392
|
-
if Str := getattr(ast, "Str", None):
|
|
393
|
-
self.nodes[Str] = self._eval_str
|
|
394
|
-
|
|
395
|
-
if NameConstant := getattr(ast, "NameConstant", None):
|
|
396
|
-
self.nodes[NameConstant] = self._eval_constant
|
|
397
|
-
|
|
398
|
-
# Defaults:
|
|
399
|
-
|
|
400
|
-
self.ATTR_INDEX_FALLBACK = ATTR_INDEX_FALLBACK
|
|
401
|
-
|
|
402
|
-
# Check for forbidden functions:
|
|
403
|
-
|
|
404
|
-
for f in self.functions.values():
|
|
405
|
-
if f in DISALLOW_FUNCTIONS:
|
|
406
|
-
raise FeatureNotAvailable("This function {} is a really bad idea.".format(f))
|
|
407
|
-
|
|
408
|
-
def __del__(self):
|
|
409
|
-
self.nodes = None
|
|
410
|
-
|
|
411
|
-
@staticmethod
|
|
412
|
-
def parse(expr):
|
|
413
|
-
"""parse an expression into a node tree"""
|
|
414
|
-
|
|
415
|
-
parsed = ast.parse(expr.strip())
|
|
416
|
-
|
|
417
|
-
if not parsed.body:
|
|
418
|
-
raise InvalidExpression("Sorry, cannot evaluate empty string")
|
|
419
|
-
if len(parsed.body) > 1:
|
|
420
|
-
warnings.warn(
|
|
421
|
-
"'{}' contains multiple expressions. Only the first will be used.".format(expr),
|
|
422
|
-
MultipleExpressions,
|
|
423
|
-
)
|
|
424
|
-
return parsed.body[0]
|
|
425
|
-
|
|
426
|
-
def eval(self, expr, previously_parsed=None):
|
|
427
|
-
"""evaluate an expression, using the operators, functions and
|
|
428
|
-
names previously set up."""
|
|
429
|
-
|
|
430
|
-
# set a copy of the expression aside, so we can give nice errors...
|
|
431
|
-
self.expr = expr
|
|
432
|
-
|
|
433
|
-
return self._eval(previously_parsed or self.parse(expr))
|
|
434
|
-
|
|
435
|
-
def _eval(self, node):
|
|
436
|
-
"""The internal evaluator used on each node in the parsed tree."""
|
|
437
|
-
|
|
438
|
-
try:
|
|
439
|
-
handler = self.nodes[type(node)]
|
|
440
|
-
except KeyError:
|
|
441
|
-
raise FeatureNotAvailable(
|
|
442
|
-
"Sorry, {0} is not available in this " "evaluator".format(type(node).__name__)
|
|
443
|
-
)
|
|
444
|
-
|
|
445
|
-
return handler(node)
|
|
446
|
-
|
|
447
|
-
def _eval_expr(self, node):
|
|
448
|
-
return self._eval(node.value)
|
|
449
|
-
|
|
450
|
-
def _eval_assign(self, node):
|
|
451
|
-
warnings.warn(
|
|
452
|
-
"Assignment ({}) attempted, but this is ignored".format(self.expr), AssignmentAttempted
|
|
453
|
-
)
|
|
454
|
-
return self._eval(node.value)
|
|
455
|
-
|
|
456
|
-
def _eval_aug_assign(self, node):
|
|
457
|
-
warnings.warn(
|
|
458
|
-
"Assignment ({}) attempted, but this is ignored".format(self.expr), AssignmentAttempted
|
|
459
|
-
)
|
|
460
|
-
return self._eval(node.value)
|
|
461
|
-
|
|
462
|
-
@staticmethod
|
|
463
|
-
def _eval_import(node):
|
|
464
|
-
raise FeatureNotAvailable("Sorry, 'import' is not allowed.")
|
|
465
|
-
|
|
466
|
-
@staticmethod
|
|
467
|
-
def _eval_num(node):
|
|
468
|
-
return node.n
|
|
469
|
-
|
|
470
|
-
@staticmethod
|
|
471
|
-
def _eval_str(node):
|
|
472
|
-
if len(node.s) > MAX_STRING_LENGTH:
|
|
473
|
-
raise IterableTooLong(
|
|
474
|
-
"String Literal in statement is too long! ({0}, when {1} is max)".format(
|
|
475
|
-
len(node.s), MAX_STRING_LENGTH
|
|
476
|
-
)
|
|
477
|
-
)
|
|
478
|
-
return node.s
|
|
479
|
-
|
|
480
|
-
@staticmethod
|
|
481
|
-
def _eval_constant(node):
|
|
482
|
-
if hasattr(node.value, "__len__") and len(node.value) > MAX_STRING_LENGTH:
|
|
483
|
-
raise IterableTooLong(
|
|
484
|
-
"Literal in statement is too long! ({0}, when {1} is max)".format(
|
|
485
|
-
len(node.value), MAX_STRING_LENGTH
|
|
486
|
-
)
|
|
487
|
-
)
|
|
488
|
-
return node.value
|
|
489
|
-
|
|
490
|
-
def _eval_unaryop(self, node):
|
|
491
|
-
try:
|
|
492
|
-
operator = self.operators[type(node.op)]
|
|
493
|
-
except KeyError:
|
|
494
|
-
raise OperatorNotDefined(node.op, self.expr)
|
|
495
|
-
return operator(self._eval(node.operand))
|
|
496
|
-
|
|
497
|
-
def _eval_binop(self, node):
|
|
498
|
-
try:
|
|
499
|
-
operator = self.operators[type(node.op)]
|
|
500
|
-
except KeyError:
|
|
501
|
-
raise OperatorNotDefined(node.op, self.expr)
|
|
502
|
-
return operator(self._eval(node.left), self._eval(node.right))
|
|
503
|
-
|
|
504
|
-
def _eval_boolop(self, node):
|
|
505
|
-
to_return = False
|
|
506
|
-
if isinstance(node.op, ast.And):
|
|
507
|
-
for value in node.values:
|
|
508
|
-
to_return = self._eval(value)
|
|
509
|
-
if not to_return:
|
|
510
|
-
break
|
|
511
|
-
elif isinstance(node.op, ast.Or):
|
|
512
|
-
for value in node.values:
|
|
513
|
-
to_return = self._eval(value)
|
|
514
|
-
if to_return:
|
|
515
|
-
break
|
|
516
|
-
return to_return
|
|
517
|
-
|
|
518
|
-
def _eval_compare(self, node):
|
|
519
|
-
right = self._eval(node.left)
|
|
520
|
-
to_return = True
|
|
521
|
-
for operation, comp in zip(node.ops, node.comparators):
|
|
522
|
-
if not to_return:
|
|
523
|
-
break
|
|
524
|
-
left = right
|
|
525
|
-
right = self._eval(comp)
|
|
526
|
-
to_return = self.operators[type(operation)](left, right)
|
|
527
|
-
return to_return
|
|
528
|
-
|
|
529
|
-
def _eval_ifexp(self, node):
|
|
530
|
-
return self._eval(node.body) if self._eval(node.test) else self._eval(node.orelse)
|
|
531
|
-
|
|
532
|
-
def _eval_call(self, node):
|
|
533
|
-
if isinstance(node.func, ast.Attribute):
|
|
534
|
-
func = self._eval(node.func)
|
|
535
|
-
else:
|
|
536
|
-
try:
|
|
537
|
-
func = self.functions[node.func.id]
|
|
538
|
-
except KeyError:
|
|
539
|
-
raise FunctionNotDefined(node.func.id, self.expr)
|
|
540
|
-
except AttributeError:
|
|
541
|
-
raise FeatureNotAvailable("Lambda Functions not implemented")
|
|
542
|
-
|
|
543
|
-
if func in DISALLOW_FUNCTIONS:
|
|
544
|
-
raise FeatureNotAvailable("This function is forbidden")
|
|
545
|
-
|
|
546
|
-
return func(
|
|
547
|
-
*(self._eval(a) for a in node.args), **dict(self._eval(k) for k in node.keywords)
|
|
548
|
-
)
|
|
549
|
-
|
|
550
|
-
def _eval_keyword(self, node):
|
|
551
|
-
return node.arg, self._eval(node.value)
|
|
552
|
-
|
|
553
|
-
def _eval_name(self, node):
|
|
554
|
-
try:
|
|
555
|
-
# This happens at least for slicing
|
|
556
|
-
# This is a safe thing to do because it is impossible
|
|
557
|
-
# that there is a true expression assigning to none
|
|
558
|
-
# (the compiler rejects it, so you can't even
|
|
559
|
-
# pass that to ast.parse)
|
|
560
|
-
return self.names[node.id]
|
|
561
|
-
|
|
562
|
-
except (TypeError, KeyError):
|
|
563
|
-
pass
|
|
564
|
-
|
|
565
|
-
if callable(self.names):
|
|
566
|
-
try:
|
|
567
|
-
return self.names(node)
|
|
568
|
-
except NameNotDefined:
|
|
569
|
-
pass
|
|
570
|
-
elif not hasattr(self.names, "__getitem__"):
|
|
571
|
-
raise InvalidExpression(
|
|
572
|
-
'Trying to use name (variable) "{0}"'
|
|
573
|
-
' when no "names" defined for'
|
|
574
|
-
" evaluator".format(node.id)
|
|
575
|
-
)
|
|
576
|
-
|
|
577
|
-
if node.id in self.functions:
|
|
578
|
-
return self.functions[node.id]
|
|
579
|
-
|
|
580
|
-
raise NameNotDefined(node.id, self.expr)
|
|
581
|
-
|
|
582
|
-
def _eval_subscript(self, node):
|
|
583
|
-
container = self._eval(node.value)
|
|
584
|
-
key = self._eval(node.slice)
|
|
585
|
-
# Currently if there's a KeyError, that gets raised straight up.
|
|
586
|
-
# TODO: Should that be wrapped in an InvalidExpression?
|
|
587
|
-
return container[key]
|
|
588
|
-
|
|
589
|
-
def _eval_attribute(self, node):
|
|
590
|
-
for prefix in DISALLOW_PREFIXES:
|
|
591
|
-
if node.attr.startswith(prefix):
|
|
592
|
-
raise FeatureNotAvailable(
|
|
593
|
-
"Sorry, access to __attributes "
|
|
594
|
-
" or func_ attributes is not available. "
|
|
595
|
-
"({0})".format(node.attr)
|
|
596
|
-
)
|
|
597
|
-
if node.attr in DISALLOW_METHODS:
|
|
598
|
-
raise FeatureNotAvailable(
|
|
599
|
-
"Sorry, this method is not available. " "({0})".format(node.attr)
|
|
600
|
-
)
|
|
601
|
-
# eval node
|
|
602
|
-
node_evaluated = self._eval(node.value)
|
|
603
|
-
|
|
604
|
-
# Maybe the base object is an actual object, not just a dict
|
|
605
|
-
try:
|
|
606
|
-
return getattr(node_evaluated, node.attr)
|
|
607
|
-
except (AttributeError, TypeError):
|
|
608
|
-
pass
|
|
609
|
-
|
|
610
|
-
# TODO: is this a good idea? Try and look for [x] if .x doesn't work?
|
|
611
|
-
if self.ATTR_INDEX_FALLBACK:
|
|
612
|
-
try:
|
|
613
|
-
return node_evaluated[node.attr]
|
|
614
|
-
except (KeyError, TypeError):
|
|
615
|
-
pass
|
|
616
|
-
|
|
617
|
-
# If it is neither, raise an exception
|
|
618
|
-
raise AttributeDoesNotExist(node.attr, self.expr)
|
|
619
|
-
|
|
620
|
-
def _eval_index(self, node):
|
|
621
|
-
return self._eval(node.value)
|
|
622
|
-
|
|
623
|
-
def _eval_slice(self, node):
|
|
624
|
-
lower = upper = step = None
|
|
625
|
-
if node.lower is not None:
|
|
626
|
-
lower = self._eval(node.lower)
|
|
627
|
-
if node.upper is not None:
|
|
628
|
-
upper = self._eval(node.upper)
|
|
629
|
-
if node.step is not None:
|
|
630
|
-
step = self._eval(node.step)
|
|
631
|
-
return slice(lower, upper, step)
|
|
632
|
-
|
|
633
|
-
def _eval_joinedstr(self, node):
|
|
634
|
-
length = 0
|
|
635
|
-
evaluated_values = []
|
|
636
|
-
for n in node.values:
|
|
637
|
-
val = str(self._eval(n))
|
|
638
|
-
if len(val) + length > MAX_STRING_LENGTH:
|
|
639
|
-
raise IterableTooLong("Sorry, I will not evaluate something this long.")
|
|
640
|
-
evaluated_values.append(val)
|
|
641
|
-
return "".join(evaluated_values)
|
|
642
|
-
|
|
643
|
-
def _eval_formattedvalue(self, node):
|
|
644
|
-
if node.format_spec:
|
|
645
|
-
fmt = "{:" + self._eval(node.format_spec) + "}"
|
|
646
|
-
return fmt.format(self._eval(node.value))
|
|
647
|
-
return self._eval(node.value)
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
class EvalWithCompoundTypes(SimpleEval):
|
|
651
|
-
"""
|
|
652
|
-
SimpleEval with additional Compound Types, and their respective
|
|
653
|
-
function editions. (list, tuple, dict, set).
|
|
654
|
-
"""
|
|
655
|
-
|
|
656
|
-
_max_count = 0
|
|
657
|
-
|
|
658
|
-
def __init__(self, operators=None, functions=None, names=None):
|
|
659
|
-
super(EvalWithCompoundTypes, self).__init__(operators, functions, names)
|
|
660
|
-
|
|
661
|
-
self.functions.update(list=list, tuple=tuple, dict=dict, set=set)
|
|
662
|
-
|
|
663
|
-
self.nodes.update(
|
|
664
|
-
{
|
|
665
|
-
ast.Dict: self._eval_dict,
|
|
666
|
-
ast.Tuple: self._eval_tuple,
|
|
667
|
-
ast.List: self._eval_list,
|
|
668
|
-
ast.Set: self._eval_set,
|
|
669
|
-
ast.ListComp: self._eval_comprehension,
|
|
670
|
-
ast.GeneratorExp: self._eval_comprehension,
|
|
671
|
-
ast.DictComp: self._eval_comprehension,
|
|
672
|
-
}
|
|
673
|
-
)
|
|
674
|
-
|
|
675
|
-
def eval(self, expr, previously_parsed=None):
|
|
676
|
-
# reset _max_count for each eval run
|
|
677
|
-
self._max_count = 0
|
|
678
|
-
return super(EvalWithCompoundTypes, self).eval(expr, previously_parsed)
|
|
679
|
-
|
|
680
|
-
def _eval_dict(self, node):
|
|
681
|
-
result = {}
|
|
682
|
-
|
|
683
|
-
for key, value in zip(node.keys, node.values):
|
|
684
|
-
if key is None:
|
|
685
|
-
# "{**x}" gets parsed as a key-value pair of (None, Name(x))
|
|
686
|
-
result.update(self._eval(value))
|
|
687
|
-
else:
|
|
688
|
-
result[self._eval(key)] = self._eval(value)
|
|
689
|
-
|
|
690
|
-
return result
|
|
691
|
-
|
|
692
|
-
def _eval_list(self, node):
|
|
693
|
-
result = []
|
|
694
|
-
|
|
695
|
-
for item in node.elts:
|
|
696
|
-
if isinstance(item, ast.Starred):
|
|
697
|
-
result.extend(self._eval(item.value))
|
|
698
|
-
else:
|
|
699
|
-
result.append(self._eval(item))
|
|
700
|
-
|
|
701
|
-
return result
|
|
702
|
-
|
|
703
|
-
def _eval_tuple(self, node):
|
|
704
|
-
return tuple(self._eval(x) for x in node.elts)
|
|
705
|
-
|
|
706
|
-
def _eval_set(self, node):
|
|
707
|
-
return set(self._eval(x) for x in node.elts)
|
|
708
|
-
|
|
709
|
-
def _eval_comprehension(self, node):
|
|
710
|
-
if isinstance(node, ast.DictComp):
|
|
711
|
-
to_return = {}
|
|
712
|
-
else:
|
|
713
|
-
to_return = []
|
|
714
|
-
|
|
715
|
-
extra_names = {}
|
|
716
|
-
|
|
717
|
-
previous_name_evaller = self.nodes[ast.Name]
|
|
718
|
-
|
|
719
|
-
def eval_names_extra(node):
|
|
720
|
-
"""
|
|
721
|
-
Here we hide our extra scope for within this comprehension
|
|
722
|
-
"""
|
|
723
|
-
if node.id in extra_names:
|
|
724
|
-
return extra_names[node.id]
|
|
725
|
-
return previous_name_evaller(node)
|
|
726
|
-
|
|
727
|
-
self.nodes.update({ast.Name: eval_names_extra})
|
|
728
|
-
|
|
729
|
-
def recurse_targets(target, value):
|
|
730
|
-
"""
|
|
731
|
-
Recursively (enter, (into, (nested, name), unpacking)) = \
|
|
732
|
-
and, (assign, (values, to), each
|
|
733
|
-
"""
|
|
734
|
-
if isinstance(target, ast.Name):
|
|
735
|
-
extra_names[target.id] = value
|
|
736
|
-
else:
|
|
737
|
-
for t, v in zip(target.elts, value):
|
|
738
|
-
recurse_targets(t, v)
|
|
739
|
-
|
|
740
|
-
def do_generator(gi=0):
|
|
741
|
-
g = node.generators[gi]
|
|
742
|
-
for i in self._eval(g.iter):
|
|
743
|
-
self._max_count += 1
|
|
744
|
-
|
|
745
|
-
if self._max_count > MAX_COMPREHENSION_LENGTH:
|
|
746
|
-
raise IterableTooLong("Comprehension generates too many elements")
|
|
747
|
-
recurse_targets(g.target, i)
|
|
748
|
-
if all(self._eval(iff) for iff in g.ifs):
|
|
749
|
-
if len(node.generators) > gi + 1:
|
|
750
|
-
do_generator(gi + 1)
|
|
751
|
-
else:
|
|
752
|
-
if isinstance(to_return, dict):
|
|
753
|
-
to_return[self._eval(node.key)] = self._eval(node.value)
|
|
754
|
-
elif isinstance(to_return, list):
|
|
755
|
-
to_return.append(self._eval(node.elt))
|
|
756
|
-
|
|
757
|
-
try:
|
|
758
|
-
do_generator()
|
|
759
|
-
finally:
|
|
760
|
-
self.nodes.update({ast.Name: previous_name_evaller})
|
|
761
|
-
|
|
762
|
-
return to_return
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
def simple_eval(expr, operators=None, functions=None, names=None):
|
|
766
|
-
"""Simply evaluate an expression"""
|
|
767
|
-
s = SimpleEval(operators=operators, functions=functions, names=names)
|
|
768
|
-
return s.eval(expr)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|