Python序列化词法闭包? [英] Python serialize lexical closures?
问题描述
有没有一种使用标准库在Python中序列化词法闭包的方法? pickle和marshal似乎不适用于词汇闭包。我并不真正在乎二进制与字符串序列化等细节,它只需要工作即可。例如:
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example:
def foo(bar, baz) :
def closure(waldo) :
return baz * waldo
return closure
我只想转储的实例
编辑:
可以解决此问题的一种相对明显的方法是使用一些反射技巧将词法闭包转换为类对象,反之亦然。然后可以将其转换为类,进行序列化,反序列化,再转换回闭包。哎呀,考虑到Python是鸭子类型的,如果您重载该类的函数调用运算符以使其看起来像一个函数,那么您甚至根本不需要将其转换回闭包,并且使用它的代码也不知道区别。如果有Python反射API专家,请大声说出来。
One relatively obvious way that this could be solved is with some reflection hacks to convert lexical closures into class objects and vice-versa. One could then convert to classes, serialize, unserialize, convert back to closures. Heck, given that Python is duck typed, if you overloaded the function call operator of the class to make it look like a function, you wouldn't even really need to convert it back to a closure and the code using it wouldn't know the difference. If any Python reflection API gurus are out there, please speak up.
推荐答案
如果您仅使用带有<$ c的类首先使用$ c> __ call __ 方法,使用 pickle
都可以顺利工作。
If you simply use a class with a __call__
method to begin with, it should all work smoothly with pickle
.
class foo(object):
def __init__(self, bar, baz):
self.baz = baz
def __call__(self,waldo):
return self.baz * waldo
由于 pickle
处理类和实例的方式,在运行时关闭新类实例的关闭将无法进行。 pickle
不存储课程;仅模块名称和类名称。当读回实例或类时,它将尝试导入模块并在其中找到所需的类。如果您使用的是即时创建的课程,那么您就不走运了。
On the other hand, a hack which converted a closure into an instance of a new class created at runtime would not work, because of the way pickle
deals with classes and instances. pickle
doesn't store classes; only a module name and class name. When reading back an instance or class it tries to import the module and find the required class in it. If you used a class created on-the-fly, you're out of luck.
这篇关于Python序列化词法闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!