0

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 where I need to create the cells to create the function, but I may not be able to finalize the values I want the cells to have until after the function is created. (As a mad example, what if I want to put the function itself in one of its cells?)

Is there a way to set the cell_contents of a cell? I tried assigning to it, but I get an AttributeError claiming cell_contents isn't writable!

EDIT: I just realized that cell_contents is writable in the latest version of Python3 (3.7), albeit not in the latest pypy (3.6) version, which I'm using.

secondperson
  • 148
  • 1
  • 4
  • I just realized that cell_contents is writable in the latest version of Python 3.x, albeit not in the latest pypy version, which I'm using. I waited too long to ask/answer this question. oh well - it's still useful for pypy until they upgrade. – secondperson Dec 10 '19 at 23:39

1 Answers1

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.)

secondperson
  • 148
  • 1
  • 4