简体   繁体   中英

Assign *args while using **kwargs

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?

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.

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]},)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM