Packing named arguments in a dict

I know that I can turn function arguments into a dictionary if the function accepts **kwargs .

 def bar(**kwargs): return kwargs print bar(a=1, b=2) {'a': 1, 'b': 2} 

But is the opposite true? Can I pack named arguments into a dictionary and return them? Manual encoding is as follows:

 def foo(a, b): return {'a': a, 'b': b} 

But there seems to be a better way. Note that I'm trying to avoid using **kwargs in a function (named arguments work better for IDEs with code completion).

+7
python dictionary kwargs
source share
1 answer

Looks like you are looking for 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} >>> 

Note that this will return a dictionary of all names in the foo scope:

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

This should not be a problem if your functions are similar to the data in your question. If so, you can use inspect.getfullargspec and a dictionary understanding to filter 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} >>> 
+9
source share

All Articles