8

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).

Felix
  • 2,064
  • 3
  • 21
  • 31
  • `return locals()` once you don't have any other variables in your code – Padraic Cunningham Oct 21 '14 at 21:07
  • [this](http://stackoverflow.com/a/582206/432913) answer to the same question has a comment underneath linking to [this](http://kbyanc.blogspot.co.uk/2007/07/python-aggregating-function-arguments.html) blog post, which does what you want, and takes care or an edge cases which iCodez's answer misses. – will Oct 21 '14 at 21:10

1 Answers1

10

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}
>>>
  • Thanks for the disclaimer; I am looking for this functionality within a class, so I'm making the method static. – Felix Oct 21 '14 at 21:27