开发者

Advantages of using *args in python instead of passing a list as a parameter

I'm going through python and I was wondering what are the advantag开发者_运维百科es of using the *args as a parameter over just passing a list as a parameter, besides aesthetics?


Generally it's used to either pass a list of arguments to a function that would normally take a fixed number of arguments, or in function definitions to allow a variable number of arguments to be passed in the style of normal arguments. For instance, the print() function uses varargs so that you can do things like print(a,b,c).

One example from a recent SO question: you can use it to pass a list of range() result lists to itertools.product() without having to know the length of the list-of-lists.

Sure, you could write every library function to look like this:

def libfunc1(arglist):
    arg1 = arglist[1]
    arg2 = arglist[2]
    ...

...but that defeats the point of having named positional argument variables, it's basically exactly what *args does for you, and it results in redundant braces/parens, since you'd have to call a function like this:

libfunc1([arg1val,arg2val,...])

...which looks very similar to...

libfunc1(arg1val,arg2val,...)

...except with unnecessary characters, as opposed to using *args.


That is for flexibility.

It allows you to pass on the arguments, without knowing how much you need. A typical example:

def f(some, args, here): # <- this function might accept a varying nb of args
    ...

def run_f(args, *f_args):
    do_something(args)
    # run f with whatever arguments were given:
    f(*f_args)

Make sure to check out the ** keyword version.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜