Tuple parameter unpacking in 3.x

Peter Otten __peter__ at web.de
Sat Oct 4 13:14:40 CEST 2008


Nick Craig-Wood wrote:

> Martin Geisler <mg at daimi.au.dk> wrote:
> 
>>  I just tried running my code using "python2.6 -3" and got a bunch of
>> 
>>    SyntaxWarning: tuple parameter unpacking has been removed in 3.x
>> 
>>  warnings. I've read PEP-3113:
>> 
>>    http://www.python.org/dev/peps/pep-3113/
>> 
>>  but I'm still baffled as to why you guys could remove such a wonderful
>>  feature?!
> 
> I don't think many people will miss tuple unpacking in def statements.
> 
> I think the warning is probably wrong anyway - you just need to remove
> a few parens...
> 
>>    ci.addCallback(lambda (ai, bi): ai * bi)
>>    map(lambda (i, s): (field(i + 1), s), enumerate(si))
> 
> On
> Python 3.0rc1 (r30rc1:66499, Oct  4 2008, 11:04:33)
> 
>>>> f = lambda (ai, bi): ai * bi
>   File "<stdin>", line 1
>     f = lambda (ai, bi): ai * bi
>                ^
> SyntaxError: invalid syntax
> 
> But
> 
>>>> f = lambda ai, bi: ai * bi
>>>> f(2,3)
> 6
> 
> Likewise
> 
>>>> lambda (i, s): (field(i + 1), s)
>   File "<stdin>", line 1
>     lambda (i, s): (field(i + 1), s)
>            ^
> SyntaxError: invalid syntax
>>>> lambda i, s: (field(i + 1), s)
> <function <lambda> at 0xb7bf75ec>
>>>>
> 
> So just remove the parentheses and you'll be fine.

No, you change the function signature in the process.

f = lambda (a, b): a*b

is equivalent to

def f((a, b)): # double parens
   return a*b

and called as f(arg) where arg is an iterable with two items.

In 3.0 it has to be rewritten as

def f(ab):
    a, b = ab
    return a*b

i. e. it needs a statement and an expression and is therefore no longer
suitable for a lambda.

Peter



More information about the Python-list mailing list