【发布时间】:2019-12-17 09:26:06
【问题描述】:
我正在尝试在 Python 中显式保存 lambda 函数。明确我的意思是不引用变量(或者这是否称为静态?)。
最小工作示例:
from argparse import Namespace
from math import asin
import dill as pickle # Use 'dill' because it can pickle lambda functions, which 'pickle' cannot.
def save_data_to_file(data_to_save, file_name):
with open(file_name, 'wb') as data_to_save_file:
pickle.dump(data_to_save, data_to_save_file)
def load_data_from_file(file_name):
with open(file_name, 'rb') as data_to_save_file:
data = pickle.load(data_to_save_file)
return data
# Definition function.
constant = 1
my_function = lambda x: asin(x) + constant
# Save function.
data_to_save = {'my_function': my_function}
file_name = 'my_function.input'
save_data_to_file(data_to_save, file_name)
# Delete variables for the sake of testing correct loading of the function.
print(my_function(0.15))
del my_function
del constant
# Load function.
data_loaded_from_file = load_data_from_file(file_name)
dlff = Namespace(**data_loaded_from_file)
print(dlff.my_function(0.15)) # NameError: name 'constant' is not defined
我收到错误 NameError: name 'constant' is not defined。所以我想要保存my_function,以便它使用一次constant,但在定义后不再需要它。这样,我就可以加载my_function,而不会让Python 抱怨不知道constant。
我如何做到这一点?
【问题讨论】:
-
不相关,但您不应该使用
lambda来定义命名函数 - 这就是def语句的用途。 -
为什么不能使用普通函数,默认值为
constant=0,def func(x,constant=0):return asin(x) + constant,如果你想添加一个常量,把它传递给函数跨度>