Question

Unpacking argument lists:

def send(*data):
    for datum in data:
        ser.write(datum)

vs sending in a list in the first place:

def send(data):
    for datum in data:
        ser.write(datum)
Was it helpful?

Solution

When it simplifies the API for the case where otherwise you'll always have to pass in a list:

send(something, otherthing)

versus:

send([something, otherthing])

where your usual parameters are taken from different locations; e.g. something and otherthing are more likely to be separate variables than already collected in one list.

The Python 3.x print() function does exactly that, as well as the os.path.join() function. You rarely have all your print arguments or path-elements-to-join combined in a list before calling the API.

Compare:

os.path.join(rootdirectory, relativepath, filename)
print('Debug information:', localvariable)

vs.

os.path.join([rootdirectory, relativepath, filename])
print(['Debug information:', localvariable])

If .join() or print() were to accept only one positional argument (a list), the users of the API would find themselves typing the [ and ] brackets over and over again.

By accepting a variable number of positional arguments, you save users of your API the trouble of having to create list just for the function call. In the rare cases where the parameters have already been collected into a list, they can use the *params calling convention:

send(*params)

to echo your function signature.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top