Django:缓存包含lambda函数的字典

2024-04-23 08:50:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django.core.cache中保存一个包含lambda函数的字典。下面的例子无声地失败了。在

from django.core.cache import cache
cache.set("lambda", {"name": "lambda function", "function":lambda x: x+1})

cache.get("lambda")
#None

我在为这种行为寻找解释。另外,我想知道是否有不使用def的解决方法。在


Tags: djangolambda函数namefromcoreimportnone
1条回答
网友
1楼 · 发布于 2024-04-23 08:50:49

The example below fails silently.

不,不会的。cache.set()调用应该会给出如下错误:

PicklingError: Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

为什么?在内部,Django使用Python的pickle库来序列化您试图存储在缓存中的值。当您想用cache.get()调用再次将其从缓存中拉出时,Django需要确切地知道如何重建缓存的值。由于不希望丢失信息或错误/不正确地重建缓存值,有几个restrictions可以对哪些类型的对象进行pickle。您会注意到只有这些类型的函数可以被pickle:

  • 在模块顶层定义的函数
  • 在模块顶层定义的内置函数

关于酸洗功能的工作原理还有以下进一步的解释:

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised.

相关问题 更多 >