tags:

views:

472

answers:

2

Is there a way to expand a Python tuple into a function - as actual parameters?

For example, here expand() does the magic:

tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(tuple)) # (2, "foobar", "barfoo")

I know one could define myfun as "myfun((a, b, c))", but of course there may be legacy code. Thanks

+8  A: 

myfun(*tuple) does exactly what you request.

Side issue: don't use as your identifiers builtin type names such as tuple, list, file, set, and so forth -- it's horrible practice and it will come back and byte you when you least expect it, so just get into the habit of actively avoiding hiding builtin names with your own identifiers.

Alex Martelli
Yes, sorry. I know it's a bad practice and was just as example.Thank you Alex.
AkiRoss
"byte" you. hehe.
prestomation
@prestomation, congratulations for being the first to notice the hidden pun (took almost a month...!-).
Alex Martelli
+1  A: 

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

I would also consider using named parameters (and passing a dictionary) over 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.

Uri