I work with library that has function with signature f(*args, **kwargs)
.
I need to pass python dict in kwargs argument, but dict contains not strings in keywords
f(**{1: 2, 3: 4})
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: f() keywords must be strings
How can I get around this without editing the function?
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.
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
That dictionary is empty because you have not passed any kwargs in foo1. Note that you should only use variable x and y. Any other variables will cause error.
**kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.
Non-string keyword arguments are simply not allowed, so there is no general solution to this problem. Your specific example can be fixed by converting the keys of your dict
to strings:
>>> kwargs = {1: 2, 3: 4}
>>> f(**{str(k): v for k, v in kwargs.items()})
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