将lambda函数保存到文件中,而无需引用其他变量/显式

问题描述 投票:0回答:1

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

我该如何实现?

python lambda static
1个回答
0
投票

如果要使常量成为函数的一部分,则必须使其成为函数的一部分:

my_function = lambda x, constant=1: asin(x) + constant
# or
my_function = lambda x: asin(x) + 1

或者,如果您绝对需要常量作为参数而不是参数,则可以使用eval来实现。我强烈建议不要这样做。

constant = 1
my_function = eval("lambda x: asin(x) " + str(constant))
© www.soinside.com 2019 - 2024. All rights reserved.