Python - Function Parameter Arguments

Introduction

* and ** in arguments support functions that take any number of arguments.

Both can appear in either the function definition or a function call.

Headers: Collecting arguments

The use in function definition collects unmatched positional arguments into a tuple:

Demo

def f(*args): print(args)

When this function is called, Python collects all the positional arguments into a new tuple and assigns the variable args to that tuple.

Because it is a normal tuple object, it can be indexed, stepped through with a for loop, and so on:

Demo

def f(*args): print(args) 
f() #   www  . ja  v a  2 s  .  c o  m
f(1) 
f(1, 2, 3, 4)

Result

The ** feature works for keyword arguments.

It collects them into a new dictionary, which can then be processed with normal dictionary tools.

The ** form allows you to convert from keywords to dictionaries:

Demo

def f(**args): print(args) 
f() 
f(a=1, b=2)

Result

You can combine normal arguments, the *, and the ** to implement flexible call signatures.

For instance, in the following, 1 is passed to a by position, 2 and 3 are collected into the pargs positional tuple, and x and y wind up in the kargs keyword dictionary:

Demo

def f(a, *pargs, **kargs): print(a, pargs, kargs) 

f(1, 2, 3, x=1, y=2)

Result

Calls: Unpacking arguments

We can use the * syntax when we call a function.

It unpacks a collection of arguments, rather than building a collection of arguments.

For example, we can pass four arguments to a function in a tuple and let Python unpack them into individual arguments:

Demo

def func(a, b, c, d): print(a, b, c, d) 

args = (1, 2) #   w ww  .ja v  a 2  s  .co m
args += (3, 4) 
func(*args)                            # Same as func(1, 2, 3, 4)

Result

The ** syntax in a function call unpacks a dictionary of key/value pairs into separate keyword arguments:

Demo

def func(a, b, c, d): print(a, b, c, d) 

args = {'a': 1, 'b': 2, 'c': 3} 
args['d'] = 4 # from  www  .  j  a v  a 2s .co  m
func(**args)                           # Same as func(a=1, b=2, c=3, d=4)

Result

We can combine normal, positional, and keyword arguments in the call in very flexible ways:

Demo

def func(a, b, c, d): print(a, b, c, d) 
func(*(1, 2), **{'d': 4, 'c': 3})      # Same as func(1, 2, d=4, c=3) 
func(1, *(2, 3), **{'d': 4})           # Same as func(1, 2, 3, d=4) 
func(1, c=3, *(2,), **{'d': 4})        # Same as func(1, 2, c=3, d=4) 
func(1, *(2, 3), d=4)                  # Same as func(1, 2, 3, d=4) 
func(1, *(2,), c=3, **{'d':4})         # Same as func(1, 2, c=3, d=4)
#  w  w w.  j  a v a 2  s .co m

Result

Related Topic