开发者

Using current scope as kwargs in python

I basically want to expand the current scope as you would a dictionary when calling a function.

I remember seeing something开发者_如何转开发 about this somewhere but I cannot remember where or how to do it.

Here is a simple example

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)

Am I imagining things or can this really be done?


You can use locals() (or globals() depending on what you need), which returns a dictionary mapping variable names to values.

bar(**locals())


if foo was written like this

def foo(**kwargs):
    bar(**kwargs)

Other than that the other two examples you posted are better, expanding all locals is a bad idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜