Can someone please explain to me when and how I would use the closure parameter of the exec function?
https://docs.python.org/3/library/functions.html#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.
It is not intended to be used when the object to be exec-ed is a string - only when it is a code object.
It happens that when one defines a function in Python, it becomes an object tthat references a code object, and some meta information that code needs to run: the globals namespace and locals namespaces for its variables - but also, if that function references any variable in an enclosing function, that is a "nonlocal" variable - that gets annotated in the
__closure__attribute of a function. When the associated code is executed, it has access to it.If there was no way to pass a
__closure__to theexecfunction, any code that would refer to non-local variables simply would not be able to run.It is possible to create a closure from "scratch", as it is simply a tuple of "cells" - each cell is a somewhat opaque handler to a Python value, and can be created with
types.CellTypeNow, onto the example: