placing python tuples in function signature

3.4k Views Asked by At

In python there is this interesting, and very useful tool by which you can pattern match values from tuples on function signature.

def first((a, b)):
    return a

x = (4, 9)
first(x)
li = [(5, 4), (8, 9)]
map(first, li)

def second(a, b):
    # does not work the same way
    return b

I don't see any literature on use of this. What is the vocabulary the python community uses for this? Is there a compelling reason to not use this?

3

There are 3 best solutions below

0
On BEST ANSWER

It's called tuple parameter unpacking and was removed in Python 3.0.

Like @zondo said, you might not want to use it for compatibility reasons. I myself still use it occasionally in Python 2. You'll find reasons against it in the PEP of my first link, though keep in mind that those are the reasons it got removed from the language, and I think it was at least partially because it made things easier for the Python makers, which is not necessarily a reason for you or me to avoid it.

0
On

In Python2, that's great. It is invalid syntax in Python3, however, so I would not recommend it for forward-compatability reasons.

0
On

The accepted answer doesn't show how to work around this, so let me just spell it out.

The Python 2 code

def fun(a, (b, c), d):
    print("a {0} b {1} c {2} d {3}".format(a, b, c, d))

can be refactored into

def fun(a, _args, d):
    b, c = _args
    print("a {0} b {1} c {2} d {3}".format(a, b, c, d))

which is also valid Python 3 code.

Call it like

fun(1, [2, 3], 4)

The linked PEP-3113 explains this in more detail, and provides the rationale for why this syntax was removed in Python 3.0.