Skip to content

Commit

Permalink
support default argument in next built-in function (#131)
Browse files Browse the repository at this point in the history
Fixes TypeError: guarded_next() takes exactly 1 argument (2 given) when using next(iter, default) in restricted environment.
  • Loading branch information
perrinjerome committed Aug 25, 2022
1 parent 708db4b commit 6d7d441
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Expand Up @@ -7,6 +7,7 @@ For changes before version 3.0, see ``HISTORY.rst``.
----------------

- Add support for Python 3.11 (as of 3.11.0a6).
- Support ``default`` argument in ``next`` built-in function.


5.3.1 (2022-03-29)
Expand Down
7 changes: 5 additions & 2 deletions src/AccessControl/ZopeGuards.py
Expand Up @@ -254,8 +254,11 @@ def _check_list_access(name, value):
# iterator that is known to be safe (as in guarded_enumerate).


def guarded_next(iterator):
ob = next(iterator)
def guarded_next(iterator, default=_marker):
if default is _marker:
ob = next(iterator)
else:
ob = next(iterator, default)
if not isinstance(iterator, SafeIter):
guard(ob, ob)
return ob
Expand Down
31 changes: 31 additions & 0 deletions src/AccessControl/tests/testZopeGuards.py
Expand Up @@ -878,6 +878,37 @@ def test_guarded_next__1(self):

self.assertEqual(its_globals['result'], 2411)

def test_guarded_next_default(self):
"""There is a `safe_builtin` named `next` with `default`."""
SCRIPT = "result = next(iterator, 'default')"

code, its_globals = self._compile_str(SCRIPT, 'ignored')
its_globals['iterator'] = iter([])

sm = SecurityManager()
old = self.setSecurityManager(sm)
try:
exec(code, its_globals)
finally:
self.setSecurityManager(old)
self.assertEqual(its_globals['result'], "default")

def test_guarded_next_StopIteration(self):
"""There is a `safe_builtin` named `next`, raising StopIteration
when iterator is exhausted."""
SCRIPT = "result = next(iterator)"

code, its_globals = self._compile_str(SCRIPT, 'ignored')
its_globals['iterator'] = iter([])

sm = SecurityManager()
old = self.setSecurityManager(sm)
with self.assertRaises(StopIteration):
try:
exec(code, its_globals)
finally:
self.setSecurityManager(old)

def test_guarded_next__2(self):
"""It guards the access during iteration."""
from AccessControl import Unauthorized
Expand Down

0 comments on commit 6d7d441

Please sign in to comment.