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

Django: cache a dictionary containing a lambda function

我正在尝试在 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.

的解决方法

The example below fails silently.

不,不是。 cache.set() 调用应该给你一个错误,如:

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

为什么?在内部,Django 使用 Python 的 pickle library to serialize the value you are attempting to store in cache. When you want to pull it out of cache again with your cache.get() call, Django needs to know exactly how to reconstruct the cached value. And due to this desire not to lose information or incorrectly/improperly reconstruct a cached value, there are several restrictions 来确定可以 pickle 的对象类型。您会注意到,只有 这些类型的函数可能被腌制:

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

还有关于 pickling 函数如何工作的进一步解释:

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.