The Python Oracle

Expanding tuples into arguments

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 Expanding Tuples Into Arguments
00:26 Accepted Answer Score 993
00:44 Answer 2 Score 16
01:12 Answer 3 Score 81
01:20 Answer 4 Score 9
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/1993...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #tuples #parameterpassing

#avk47



ACCEPTED ANSWER

Score 993


myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.




ANSWER 2

Score 81


Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))



ANSWER 3

Score 16


Take a look at the Python tutorial section 4.7.3 and 4.7.4. It talks about passing tuples as arguments.

I would also consider using named parameters (and passing a dictionary) instead of using a tuple and passing a sequence. I find the use of positional arguments to be a bad practice when the positions are not intuitive or there are multiple parameters.




ANSWER 4

Score 9


This is the functional programming method. It lifts the tuple expansion feature out of syntax sugar:

apply_tuple = lambda f, t: f(*t)

Redefine apply_tuple via curry to save a lot of partial calls in the long run:

from toolz import curry
apply_tuple = curry(apply_tuple)

Example usage:

from operator import add, eq
from toolz import thread_last

thread_last(
    [(1,2), (3,4)],
    (map, apply_tuple(add)),
    list,
    (eq, [3, 7])
)
# Prints 'True'