Expanding tuples into arguments
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Isolated
--
Chapters
00:00 Question
00:32 Accepted answer (Score 927)
00:56 Answer 2 (Score 73)
01:09 Answer 3 (Score 16)
01:42 Answer 4 (Score 11)
02:19 Thank you
--
Full question
https://stackoverflow.com/questions/1993...
Accepted answer links:
[unpacking arguments]: https://docs.python.org/3/tutorial/contr...
Answer 3 links:
[the Python tutorial]: http://docs.python.org/tutorial/controlf...
Answer 4 links:
[curry]: http://toolz.readthedocs.io/en/latest/ap...
--
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'