简体   繁体   中英

Is there an advantage to using *args over **kwargs in python?

So I understand the difference between *args and **kwargs and I use **kwargs regularly in my functions to pass optional arguments. However I never seem to use args because I don't want two of the same argument type to be passed to the function, or I don't want to have to rely on positional inputs to the function, or a variety of other more context specific reasons for using **kwargs over *args.

Is there a scenario, or a type of use case where using *args would be preferable to using **kwargs?

*args would be preferable for any function that performs an operation over an array with no limit, for example:

def add(*args):
    total = 0
    for num in args:
        total = total + num
    return total

I can call add with any amount of parameters:

add(1, 2, 2) #  5
add(1) #  1
add(1, 2, 3, 4, 5, 6, 7) #  28

Consider itertools.chain .

Thanks to *args , you can:

itertools.chain([1,2,3], ['a', 'b', 'c'], [True, False, False])

If we would opt to use **kwargs instead of *args , we would need to define some kind of naming standard so the user can pass in as many iterables as he/she wants.

The calling code would end up being something like this:

itertools.chain(seq1=[1,2,3], seq2=['a','b','c'], seq3=[True, False, False])

Which isn't really nice at all.

So, *args is really useful when dealing with an unknown length of arguments.

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