Allow __enter__ and __exit__ as restricted method names - #333
afonsojanu wants to merge 1 commit into
Conversation
The transformer's ALLOWED_FUNC_NAMES allowlist only covered __init__ and the rich comparison dunders, so any class defined in restricted code that implemented the context manager protocol failed to compile with "__enter__ is an invalid variable name because it starts with _" (and likewise for __exit__), even though the with statement itself is already supported by the transformer. Reproduced first against the unpatched code: compiling a class with an __enter__/__exit__ pair raised exactly that SyntaxError. Adding both names to ALLOWED_FUNC_NAMES lets such a class compile, and actually running it through a with statement invokes __enter__ and __exit__ in the right order around the block body. Fixes zopefoundation#230.
|
Thank you for the PR and the clear write-up. I'm sorry to change direction here, since I invited this change in #230 myself. While reviewing it, I realized that allowing On the other hand, not allowing context managers to be defined does not block anything. They are syntactic sugar for So I'm closing this PR. Thanks again for your work and sorry for the noise. |
Fixes #230.
ALLOWED_FUNC_NAMESinsrc/RestrictedPython/transformer.pyonly allowlists__init__and the rich comparison dunders (__lt__,__le__,__eq__,__ne__,__gt__,__ge__,__contains__), so any class defined in restricted code that implements__enter__/__exit__to support the context manager protocol fails to compile, with the usual "is an invalid variable name because it starts with_" error for both names.I reproduced this first: compiling the exact snippet from the issue gives that SyntaxError against the unpatched code. The
withstatement itself is already handled fine byvisit_Within the transformer, so the only actual gap is these two method names never being allowlisted. After adding__enter__and__exit__toALLOWED_FUNC_NAMES, the class compiles, and running it through an actualwithblock calls__enter__and__exit__in the right order around the body (verified with a small script and with the added test).Changes:
src/RestrictedPython/transformer.py: add__enter__and__exit__toALLOWED_FUNC_NAMES.tests/test_Guards.py: new test that defines a context manager class in restricted code and exercises it in a realwithstatement, checking__enter__/__exit__both ran in the expected order.CHANGES.rst: entry under the unreleased heading.Ran the full suite locally (
pytest tests/): 300 passed, 10 skipped, no failures.