Python dict / OrderedDict:将函数赋值给它而不立即执行它

时间:2017-09-05 11:56:22

标签: python dictionary ordereddictionary

我有一个OrderedDict,其值我想成为函数,但遇到了意外的行为。初始化:

from collections import OrderedDict

options_dict=OrderedDict(["A",call_func_A(arg1,arg2)],
                         ["B",call_func_B(arg1,arg3)],
                         ["C",call_func_C(arg1,arg4)]

# Select options
options=["A","C"]

# Execute
result={}
for opt in options:
    result[opt]=options_dict[opt]

# Return result (or whatever)
print result

函数call_func_A,call_func_B和call_func_C结果在声明options_dict时执行,而不是在后续的for循环选项中执行。

我希望函数调用等到for循环。

发生了什么?

2 个答案:

答案 0 :(得分:4)

在创建字典之前调用这些函数。你打了电话。

但是,您可以通过将函数调用嵌套在稍后调用的另一个函数中来推迟函数调用:

options_dict = OrderedDict([("A", lambda: call_func_A(arg1,arg2)),
                            ("B", lambda: call_func_B(arg1,arg3)),
                            ("C", lambda: call_func_C(arg1,arg4))])

# Select options
options = ["A", "C"]

# Execute
result = {}
for opt in options:
    result[opt] = options_dict[opt]() # <- call

使用functools.partial可以实现相同的效果,并执行额外的import语句。

另一方面,由于您的函数参数可能是不变,因此我不认为何时进行调用很重要。你也可以保留你在dict创建时调用函数的初始方法。

答案 1 :(得分:1)

首先,您正在声明OrderedDict错误。构造函数需要一个元组列表。相反,你给它多个列表。这样做:

options_dict=OrderedDict([("A",call_func_A(arg1, arg2)),
                          ("B",call_func_B(arg1, arg3)),
                          ("C",call_func_C(arg1, arg4))])

其次,当您声明options_dict时,您不会将函数作为dict的值传递,而是传递它们的结果:

options_dict=OrderedDict(["A",call_func_A(arg1,arg2)],
                         ["B",call_func_B(arg1,arg3)],
                         ["C",call_func_C(arg1,arg4)])

您通过call_func_A(arg1, arg2) 呼叫他们。一种相对简单的避免方法是省略args:

options_dict=OrderedDict([("A",call_func_A),
                         ("B",call_func_B),
                         ("C",call_func_C)])

您可以将args存储在第二个OrderedDict中:

args_dict=OrderedDict([("A",[arg1, arg2]),
                      ("B",[arg3, arg4]),
                      ("C",[arg5, arg6])])

然后给他们打电话:

result={}
for opt in options:
    result[opt]=options_dict[opt](*args_dict[opt])
相关问题