Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use packed *args/**kwargs instead of passing list/dict?

If I don't know how many arguments a function will be passed, I could write the function using argument packing:

def add(factor, *nums):
    """Add numbers and multiply by factor."""
    return sum(nums) * factor

Alternatively, I could avoid argument packing by passing a list of numbers as the argument:

def add(factor, nums):
    """Add numbers and multiply by factor.

    :type factor: int
    :type nums: list of int
    """
    return sum(nums) * factor

Is there an advantage to using argument packing *args over passing a list of numbers? Or are there situations where one is more appropriate?

like image 486
DBedrenko Avatar asked Nov 05 '15 11:11

DBedrenko


People also ask

Should I use args or Kwargs?

Ordering Arguments in a Function Just as non-default arguments have to precede default arguments, so *args must come before **kwargs . To recap, the correct order for your parameters is: Standard arguments. *args arguments.

Why do we use args and Kwargs?

We use *args and **kwargs as an argument when we are unsure about the number of arguments to pass in the functions.

Why do we use Kwargs in Python?

**kwargs allows us to pass a variable number of keyword arguments to a Python function. In the function, we use the double-asterisk ( ** ) before the parameter name to denote this type of argument.

Can you pass a dictionary to Kwargs?

You cannot directly send a dictionary as a parameter to a function accepting kwargs. The dictionary must be unpacked so that the function may make use of its elements. This is done by unpacking the dictionary, by placing ** before the dictionary name as you pass it into the function.


1 Answers

*args/**kwargs has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones. Python 3's print() is a good example.

print('hi')
print('you have', num, 'potatoes')
print(*mylist)

Contrast that with what it would be like if print() only took a packed structure and then expanded it within the function:

print(('hi',))
print(('you have', num, 'potatoes'))
print(mylist)

In this case, *args/**kwargs comes in really handy.

Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as sum() and str.join() do, it might make more sense to leave out the * syntax.

like image 89
TigerhawkT3 Avatar answered Oct 14 '22 13:10

TigerhawkT3