gh-92203: Add closure support to exec(). (#92204)

Add a closure keyword-only parameter to exec(). It can only be specified when exec-ing a code object that uses free variables. When specified, it must be a tuple, with exactly the number of cell variables referenced by the code object. closure has a default value of None, and it must be None if the code object doesn't refer to any free variables.
This commit is contained in:
larryhastings 2022-05-06 10:09:35 -07:00 committed by GitHub
parent 973a5203c1
commit 5021064390
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 171 additions and 21 deletions

View file

@ -552,7 +552,7 @@ are always available. They are listed here in alphabetical order.
.. index:: builtin: exec
.. function:: exec(object[, globals[, locals]])
.. function:: exec(object[, globals[, locals]], *, closure=None)
This function supports dynamic execution of Python code. *object* must be
either a string or a code object. If it is a string, the string is parsed as
@ -581,6 +581,11 @@ are always available. They are listed here in alphabetical order.
builtins are available to the executed code by inserting your own
``__builtins__`` dictionary into *globals* before passing it to :func:`exec`.
The *closure* argument specifies a closure--a tuple of cellvars.
It's only valid when the *object* is a code object containing free variables.
The length of the tuple must exactly match the number of free variables
referenced by the code object.
.. audit-event:: exec code_object exec
Raises an :ref:`auditing event <auditing>` ``exec`` with the code object
@ -599,6 +604,9 @@ are always available. They are listed here in alphabetical order.
Pass an explicit *locals* dictionary if you need to see effects of the
code on *locals* after function :func:`exec` returns.
.. versionchanged:: 3.11
Added the *closure* parameter.
.. function:: filter(function, iterable)