Reputation: 23
I have a python function which looks like this:
def test(a, b, *args):
print(a, b, args)
And I have a dictionary (kwargs) which has only a and b as items in it. I would like to call test like this:
test(**kwargs)
and assign more values to args. How do I do it, and if I can't, What is the right way to do this?
Upvotes: 0
Views: 215
Reputation: 3120
You defined your function to always accept an either positional or keyword arguments: a
and b
, and a list of positional arguments after that.
In Python it's a Syntax Error to provide a positional argument after a keyword argument.
Therefore, you cannot use **kwargs
dictionary unpacking in your method call, if you also want to provide additional positional arguments.
What you can do, though, is either use positional arguments only - making sure that a
and b
are the first two elements in your list.
Or if you really wan't to use a dictionary, You'd have to directly get a
and b
values, pass it positionally as a
and b
, and then get remaining items()
from your dictionary and call your function with it. This will lose the key values though.
Upvotes: 1
Reputation: 82755
You can try using just *args
as argument.
Ex:
def test(*args):
print(args)
test({"a": 1, "b":2, "c":3, "d":[1,2,3,45]})
Output:
({'a': 1, 'c': 3, 'b': 2, 'd': [1, 2, 3, 45]},)
Upvotes: 0