Felix
Felix

Reputation: 2154

packing named arguments into a dict

I know I can turn function arguments into a dictionary if the function takes in **kwargs.

def bar(**kwargs):
    return kwargs

print bar(a=1, b=2)
{'a': 1, 'b': 2}

However, is the opposite true? Can I pack named arguments into a dictionary and return them? The hand-coded version looks like this:

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

But it seems like there must be a better way. Note that i am trying to avoid using **kwargs in the function (named arguments work better for an IDE with code completion).

Upvotes: 9

Views: 2962

Answers (1)

user2555451
user2555451

Reputation:

It sounds 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 however that this will return a dictionary of all names that are within the scope of foo:

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

This shouldn't be a problem if your functions are like that given in your question. If it is however, you can use inspect.getfullargspec and a dictionary comprehension 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}
>>>

Upvotes: 11

Related Questions