在python中使用当前范围作为kwargs

Nic*_* A. 3 python kwargs

我基本上想要扩展当前范围,就像调用函数时的字典一样.

我记得在某个地方看到过这个,但我不记得在哪里或怎么做.

这是一个简单的例子

def bar(a, b, c, d, e, f):
    pass

def foo(a, b, c, d, e, f):
    # Instead of doing this
    bar(a, b, c, d, e, f)
    # or
    bar(a=a, b=b, c=c, d=d, e=e, f=f)
    # I'd like to do this
    bar(**local_scope)
Run Code Online (Sandbox Code Playgroud)

我想象的事情还是可以做到的?

Ism*_*awi 6

您可以使用locals()(或globals()根据您的需要)返回将变量名称映射到值的字典.

bar(**locals())
Run Code Online (Sandbox Code Playgroud)