If I have a Python function defined as f(a, b, c)
, is there a straightforward way to get a dictionary mapping the formal names to the values passed in? That is, from inside f
, I'd like to be able to get a dictionary {'a': 1, 'b': 2, 'c': 3}
for the call f(1, 2, 3)
.
I'd like to do this so I can directly use the arguments and values in a string substitution, e.g. "%(a)s %(b)s %(c)s" % d
. I could just do something like d = dict(a=a, b=b, c=c)
, but I'd rather avoid the repetition if possible.
I know this is quite easy to do by defining f
as f(**kwds)
, but that also makes it less obvious what arguments the function expects. It looks like there'd probably be some way to do this via the inspect
module, but it'd probably be too complex to be worthwhile.
I suspect there's no good answer to this question as posed, but I'd be happy to be proven wrong. Alternative approaches for accomplishing what I described above would be welcome too.
Passing Dictionary as kwargs “ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.
Given a dictionary, assign its keys as function calls. Case 1 : Without Params. The way that is employed to achieve this task is that, function name is kept as dictionary values, and while calling with keys, brackets '()' are added.
Python dict() Function is used to create a Python dictionary, a collection of key-value pairs. Python3.
To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.
>>> import inspect
>>> def foo(a,b,c):
... pass
...
>>> inspect.getargspec(foo)
ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
>>> inspect.getargspec(foo).args
['a', 'b', 'c']
Now you can filter locals()
based on those.
>>> x = 'outer'
>>> G = 'GLOBAL'
>>> def foo(a, b, c=1, *splat, **splatsplat):
... global G
... d = 'inner'
... b = 'stomped'
... print(locals())
... print(inspect.getargspec(foo))
...
>>> foo(1, 2, 3, 'splat1', 'splat2', named='potato')
{'splatsplat': {'named': 'potato'}, 'splat': ('splat1', 'splat2'), 'd': 'inner', 'b': 'stomped', 'c': 3, 'a': 1}
ArgSpec(args=['a', 'b', 'c'], varargs='splat', keywords='splatsplat', defaults=(1,))
The only thing I don't know how to get is to recover the original value of b
; I think that's probably impossible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With