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

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

问题描述

我在许多线程中读到 Python pickle/cPickle 不能pickle 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,它具有一种称为 tasklets 的微线程形式,用于执行一个函数.这些 tasklet 可以被暂停、pickle、unpickled 和继续,所以我猜(在 stackless 邮件列表中询问)它也提供了一种方法来 pickle 函数体.

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 可以pickle lambda 函数……但前提是你有使用copy_reg 来注册how 用于pickle lambda 函数——当您import dill 时,包dill 会将您需要的copy_reg 加载到pickle 注册表中.>

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可以pickle lambda函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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