将命名参数打包成dict

Fel*_*lix 7 python dictionary kwargs

我知道如果函数接受,我可以将函数参数转换为字典**kwargs.

def bar(**kwargs):
    return kwargs

print bar(a=1, b=2)
{'a': 1, 'b': 2}
Run Code Online (Sandbox Code Playgroud)

但是,情况恰恰相反?我可以命名参数打包到字典中并返回它们吗?手动编码版本如下所示:

def foo(a, b):
    return {'a': a, 'b': b}
Run Code Online (Sandbox Code Playgroud)

但似乎必须有更好的方法.请注意,我试图避免**kwargs在函数中使用(命名参数对于代码完成的IDE更有效).

iCo*_*dez 9

听起来你正在寻找locals:

>>> def foo(a, b):
...     return locals()
...
>>> foo(1, 2)
{'b': 2, 'a': 1}
>>> def foo(a, b, c, d, e):
...     return locals()
...
>>> foo(1, 2, 3, 4, 5)
{'c': 3, 'b': 2, 'a': 1, 'e': 5, 'd': 4}
>>>
Run Code Online (Sandbox Code Playgroud)

但请注意,这将返回以下范围内的所有名称的字典foo:

>>> def foo(a, b):
...     x = 3
...     return locals()
...
>>> foo(1, 2)
{'b': 2, 'a': 1, 'x': 3}
>>>
Run Code Online (Sandbox Code Playgroud)

如果您的功能与问题中给出的功能类似,那么这不应该是一个问题.然而,如果是,你可以用inspect.getfullargspec字典解析过滤locals():

>>> def foo(a, b):
...     import inspect # 'inspect' is a local name
...     x = 3          # 'x' is another local name
...     args = inspect.getfullargspec(foo).args
...     return {k:v for k,v in locals().items() if k in args}
...
>>> foo(1, 2) # Only the argument names are returned
{'b': 2, 'a': 1}
>>>
Run Code Online (Sandbox Code Playgroud)