From 5c4c7f9b61b5e7a17b5f094e8206c9e2e95448ec Mon Sep 17 00:00:00 2001 From: Michael Howitz Date: Thu, 25 Jan 2018 12:26:43 +0100 Subject: [PATCH] Allow list comprehensions in ``RestrictionCapableEval.eval()``. Fixes #95. --- docs/CHANGES.rst | 5 ++++- src/RestrictedPython/Eval.py | 8 +++++++- tests/test_eval.py | 7 +++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/docs/CHANGES.rst b/docs/CHANGES.rst index 91bc291..9af2e61 100644 --- a/docs/CHANGES.rst +++ b/docs/CHANGES.rst @@ -7,6 +7,9 @@ Changes - Warn when using another Python implementation than CPython as it is not safe to use RestrictedPython with other versions than CPyton. See https://bitbucket.org/pypy/pypy/issues/2653 for PyPy. +- Allow to use list comprehensions in the default implementation of + ``RestrictionCapableEval.eval()``. + 4.0b2 (2017-09-15) ------------------ @@ -62,7 +65,7 @@ Changes - Mostly complete rewrite based on Python AST module. [loechel (Alexander Loechel), icemac (Michael Howitz), stephan-hof (Stephan Hofmockel), tlotze (Thomas Lotze)] - + - Support Python versions 3.4 up to 3.6. - switch to pytest diff --git a/src/RestrictedPython/Eval.py b/src/RestrictedPython/Eval.py index 836ea5e..221cd2d 100644 --- a/src/RestrictedPython/Eval.py +++ b/src/RestrictedPython/Eval.py @@ -35,6 +35,11 @@ def default_guarded_getitem(ob, index): return ob[index] +def default_guarded_getiter(ob): + # No restrictions. + return ob + + class RestrictionCapableEval(object): """A base class for restricted code.""" @@ -99,7 +104,8 @@ def eval(self, mapping): global_scope = { '_getattr_': default_guarded_getattr, - '_getitem_': default_guarded_getitem + '_getitem_': default_guarded_getitem, + '_getiter_': default_guarded_getiter, } global_scope.update(self.globals) diff --git a/tests/test_eval.py b/tests/test_eval.py index 0499a04..d1acf10 100644 --- a/tests/test_eval.py +++ b/tests/test_eval.py @@ -95,3 +95,10 @@ def test_Eval__RestictionCapableEval__eval_1(): ob.globals['c'] = 8 result = ob.eval(dict(a=1, b=2, c=4)) assert result == 11 + + +def test_Eval__RestictionCapableEval__eval__2(): + """It allows to use list comprehensions.""" + ob = RestrictionCapableEval("[item for item in (1, 2)]") + result = ob.eval({}) + assert result == [1, 2]