When writing Python 3.x functions, I've often stumbled upon the problem of writing code that accepts both a single value and a number of values. Take this trivial function:
def capitalize(word):
return word.capitalize()
This function works well with a single string as input, but will fail if provided with multiple strings, or a list of strings.
We could turn the function to accept a list of strings, that way it would work if provided both with one value, or multiple. Even if I passed a single value, however, it would need to be wrapped in a list, and the return value would be a list as well, even when containing one element.
def capitalize(words):
return [word.capitalize() for word in words]
I recently read up on *args, and thought i could get around the awkwardness of having to pass a single string wrapped in a list as argument to the above function by rewriting it to be like the following:
def capitalize(*words):
return [word.capitalize() for word in words]
It seems to me that this is a legittimate use of *args
. However, I found a pyCon 2015 talk in which the speaker claims "variable positional arguments are good for removing noise and make your code readable, not to turn a single call api into an N api"
https://www.youtube.com/watch?v=WjJUPxKB164 at the 5:30 mark.
Is this a reasonable use of *args? If this is not how *args
is supposed to be used, is there an established way to handle single vs multi-parameter functions?