You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
context manager methods (__enter__ and __exit__) raise a SyntaxError #230
I expected to have a context manager that I could use in a with statement
What actually happened:
I get the following error:
SyntaxError: ('Line 3: "__enter__" is an invalid variable name because it starts with "_"', 'Line 6: "__exit__" is an invalid variable name because it starts with "_"')
These methods (__enter__ and __exit__) are missing from transformer.ALLOWED_FUNC_NAMES
What version of Python and Zope/Addons I am using:
Currently you are not able to define a context manager inside restricted Python because the needed method names start with _.
But I see the value in being able to do so.
A pull request is welcome adding __enter__ and __exit__ to ALLOWED_FUNC_NAMES including a test showing that context managers can be defined and used afterwards in restricted Python.
I changed my mind about this one. See #333 for the details.
Allowing __exit__ would give restricted code the traceback object. Through it, restricted code could reach the frames of trusted code, which it cannot reach today. I think that risk is too big.
Nothing is lost by not allowing context managers to be defined in restricted code: they are syntactic sugar for try/finally, which restricted code can already use. Context managers provided by trusted code already work in with statements.
Activity
icemac commentedon Aug 24, 2022
Currently you are not able to define a context manager inside restricted Python because the needed method names start with
_.But I see the value in being able to do so.
A pull request is welcome adding
__enter__and__exit__toALLOWED_FUNC_NAMESincluding a test showing that context managers can be defined and used afterwards in restricted Python.icemac commentedon Sep 30, 2026
I changed my mind about this one. See #333 for the details.
Allowing
__exit__would give restricted code the traceback object. Through it, restricted code could reach the frames of trusted code, which it cannot reach today. I think that risk is too big.Nothing is lost by not allowing context managers to be defined in restricted code: they are syntactic sugar for
try/finally, which restricted code can already use. Context managers provided by trusted code already work inwithstatements.Closing as "won't fix".