[Python-ideas] Generator unpacking

Andrew Barnert abarnert at yahoo.com
Tue Feb 16 06:04:47 EST 2016


On Feb 16, 2016, at 02:11, Sven R. Kunze <srkunze at mail.de> wrote:
> 
>> On 16.02.2016 01:11, Andrew Barnert via Python-ideas wrote:
>> I see this more often written in tuple-ish form:
>> 
>>     index, value = struct.unpack_from('!HH', buf, off)
>>     namelen, = struct.unpack_from('!H', buf, off+4)
>> 
>> Somehow, that feels more natural and pythonic than using [index, value] and [namelen], despite the fact that without the brackets it's easy to miss the trailing comma and end up with (16,) instead of 16 as your length and a confusing TypeError a few lines down.
> 
> You are right. It seems to me that without the parentheses it's not regarded a tuple but a special feature syntax; so all the known peculiarities of tuples aren't recognized properly.

It's not a tuple _with_ the parentheses either: it's a parenthesized target list, which has a syntax and semantics that are, while not completely unrelated to tuple, definitely not the same.

One way in which it _is_ like a tuple is that this doesn't help:

    (namelen) = struct.unpack_from('!H', buf, off+4)

Just like tuples, parenthesized target lists need commas, so this will bind namelen to the tuple (16,) instead of to 16:


More information about the Python-ideas mailing list