Skip to content Skip to sidebar Skip to footer

How To Set The Content Of A Closure Cell?

The following question shows how to create a closure cell object, in order to programmatically construct functions with closures. However, there's a chicken-and-egg problem here wh

Solution 1:

On python 3.x, the following dirty trick can be done:

from types import FunctionType

def set_cell(cell, value):
    def cell_setter(value):
        nonlocal cell
        cell = value # pylint: disable=unused-variable
    func = FunctionType(cell_setter.__code__, globals(), "", None, (cell,)) # same as cell_setter, but with cell being the cell's contents
    func(value)

To expand on the comment, when func is executed, the code of cell_setter is called but with the 'cell' nonlocal mapped to the content of the cell, so assigning to it changes the cell's content.

(I am not sure if there's a way in python 2 as well without resorting to C code, as in the answer to the linked question.)


Post a Comment for "How To Set The Content Of A Closure Cell?"