Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ Changes
providing an ``__import__`` implementation hands the security boundary to the
import policy of the calling application.

- Allow defining ``__enter__`` and ``__exit__`` on a class in restricted code,
so a class can be used as a context manager in a ``with`` statement. See
`issue 230 <https://github.com/zopefoundation/RestrictedPython/issues/230>`_.


8.5 (2026-08-19)
----------------
Expand Down
2 changes: 2 additions & 0 deletions src/RestrictedPython/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
'__ne__',
'__gt__',
'__ge__',
'__enter__',
'__exit__',
])


Expand Down
31 changes: 31 additions & 0 deletions tests/test_Guards.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,37 @@ def display(self):
assert restricted_globals['result'] == '2411'


def test_Guards__safe_builtins__3():
"""It allows classes to define `__enter__` and `__exit__` so they can be
used as context managers in a `with` statement.
"""

context_manager_code = '''
class MyContextManager:
def __enter__(self):
events.append('enter')
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
events.append('exit')
return False

events = []
with MyContextManager():
events.append('inside')
result = events'''

restricted_globals = dict(
result=None,
__name__='restricted_module',
__metaclass__=type,
_write_=_write_,
_getattr_=getattr)

restricted_exec(context_manager_code, restricted_globals)
assert restricted_globals['result'] == ['enter', 'inside', 'exit']


def test_Guards__guarded_setattr__1():
"""It allows use setattr and delattr when _guarded_writes is True.
"""
Expand Down
Loading