如何在不立即执行的情况下通过函数调用传递kwargs



我想将函数参数为kwargs的函数调用dict传递给另一个函数。不幸的是,传递的函数会立即执行,而不是像下面的例子所示那样传递:

def info(info='NO INFO'):  # just a test function
print(); print(''', info, ''', sep=""); print()
kwargs = {'one': info('executed one'), 'two': info('executed two')}

结果是:

'executed one'

'executed two'

我如何才能防止这些论点被执行和传递?

您不是在传递函数,而是在传递调用函数的结果。Python必须在到达那一行时立即调用函数:kwargs = {'one': info('executed one'), 'two': info('executed two')},以了解dict中的值(在本例中,这两个值都是None——显然不是您想要的(。

正如我所说,你需要传递一个实际的函数,这可以很容易地通过(例如,还有其他方法(lambdas来完成——没有参数的lambdas并不常见,但是允许的:

kwargs = {'one': (lambda: info('executed one')), 'two': (lambda: info('executed two'))}

最新更新