Python可以腌制lambda函数吗? [英] Can Python pickle lambda functions?

查看:72
本文介绍了Python可以腌制lambda函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多线程,它们说明Python pickle/cPickle无法使lambda函数失效.但是,以下代码在使用Python 2.7.6的情况下有效:

I have read in a number of threads that Python pickle/cPickle cannot pickle lambda functions. However the following code works, using Python 2.7.6:

import cPickle as pickle

if __name__ == "__main__":
    s = pickle.dumps(lambda x, y: x+y)
    f = pickle.loads(s)
    assert f(3,4) == 7

那是怎么回事?或者说,腌制lambda的极限是什么?

So what is going on? Or, rather, what is the limit of pickling lambdas?

我想我知道为什么这段代码会运行.我忘了(对不起!)我正在运行无堆栈python,它具有一种称为tasklet的微线程形式,可以执行一个功能.这些Tasklet可以暂停,腌制,不腌制和继续进行,因此,我猜(在无堆栈邮件列表中询问),它还提供了一种腌制函数体的方法.

I think i know why this code runs. I forgot (sorry!) i am running stackless python, which has a form of micro-threads called tasklets executing a function. These tasklets can be halted, pickled, unpickled and continued, so i guess (asked on the stackless mailing list) that it also provides a way to pickle function bodies.

推荐答案

是的,python可以腌制lambda函数……但前提是您有使用copy_reg注册如何腌制lambda函数的东西. -dill软件包在您import dill时将您需要的copy_reg加载到泡菜注册表中.

Yes, python can pickle lambda functions… but only if you have something that uses copy_reg to register how to pickle lambda functions -- the package dill loads the copy_reg you need into the pickle registry for you, when you import dill.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import dill  # the code below will fail without this line
>>> 
>>> import pickle
>>> s = pickle.dumps(lambda x, y: x+y)
>>> f = pickle.loads(s)
>>> assert f(3,4) == 7
>>> f
<function <lambda> at 0x10aebdaa0>

在此处获取莳萝: https://github.com/uqfoundation

这篇关于Python可以腌制lambda函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆