Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unpacking function argument [duplicate]

if a function takes n number of arguments, and there is another function that returns a sequence with n number of items(or I have a sequence with n number of items), is there a way to 'map' these two functions(or make the first function take a sequence of n number of items as input and return result) I don't want (and maybe can't in some occasions) to edit the function myself and change its arguments parameters and return value types.

i.e)

def func1(x, y, z):
    return x+y+z

def func2(w):
    return [i for i in range(w,w+3)]

cant func1(func2( ... )) in this case.

like image 252
thkang Avatar asked Oct 08 '12 16:10

thkang


2 Answers

You are looking for the *args argument syntax:

>>> def foo(bar, baz, spam):
...     print bar, baz, spam
...
>>> arguments = [1, 2, 3]
>>> foo(*arguments)
1, 2, 3

When passing arguments to a callable, any expression preceded by a * asterix, is interpreted as a sequence of positional arguments, and expanded to be passed on as separate arguments to the called object (function, method, etc.).

For your example that would be:

func1(*func2(...))

There is a keyword equivalent using ** double asterixes (takes a mapping), and you can use the same syntax in function signatures too.

See the documentation on call expressions, and for the function signature mirror syntax, the documentation on function definitions.

like image 57
Martijn Pieters Avatar answered Nov 08 '22 12:11

Martijn Pieters


It's called argument unpacking and is written as:

func1(*func2(...))

Refer: https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists

like image 22
Jon Clements Avatar answered Nov 08 '22 11:11

Jon Clements