How to set the content of a closure cell?

ぃ、小莉子 提交于 2019-12-25 01:12:42

问题


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.


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



来源:https://stackoverflow.com/questions/59276834/how-to-set-the-content-of-a-closure-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!