Reputation: 117
I have a function (which I'll call foo) that modifies a list (which I'll call my_list). foo does not always want to modify my_list in the same way; its behavior should influenced by its other arguments (which I'll call other_inputs). Here's some pseudocode:
def foo(my_list, other_inputs):
for input in other_inputs:
my_list.bar(input)
return my_list
I can see two ways to format other_inputs.
I could use *args:
def foo(my_list, *other_inputs):
for input in other_inputs:
my_list.bar(input)
return my_list
Alternately, I could make other_inputs a list, empty by default:
def foo(my_list, other_inputs=[]):
for input in other_inputs:
my_list.bar(input)
return my_list
I've tested it on my machine and both options seem to do the same thing. Which one is preferable?
(Assume that this foo() is called many times, each time with a new other_inputs read in from some external source. Also assume that other_inputs is never appended to or mutated in any other way between external reads, so this isn't a problem.)
Upvotes: 1
Views: 89
Reputation: 531878
Since you are reading other_inputs
from another source, you presumably already have a sequence. That argues for the second approach:
def foo(my_list, other_inputs=None):
if other_inputs is not None:
# Assume other_inputs is some type of iterable
for input in other_inputs:
my_list.bar(input)
return my_list
However, you could still use the first approach and call foo
with
foo(some_list, *inputs)
It's mostly a matter of preference.
Upvotes: 1
Reputation: 16753
Obviously both of the options are correct, it would be wrong to say one of them is not.
If all other arguments passing to be function are of same type(by same type means they all change input then), then both approaches are equivalent. It is just a matter of preference as suggested by @chepner
But if there is some additional argument (say , expected length of output) which is going to be used differently from other params, then using list explicitly would be a better design.
Upvotes: 0