[Python-ideas] Generator unpacking
Andrew Barnert
abarnert at yahoo.com
Mon Feb 15 19:11:16 EST 2016
On Feb 15, 2016, at 15:43, Steven D'Aprano <steve at pearwood.info> wrote:
>
>> On Mon, Feb 15, 2016 at 06:53:45PM +0100, Sven R. Kunze wrote:
>>> On 15.02.2016 18:39, Ethan Furman wrote:
>>> I /think/ I've used that trick to confirm an iterable was empty; I
>>> /know/ I've used
>>>
>>> [some_var] = some_var
>>
>> Is that an unknown Python idiom?
>
> No, it's exactly the same Python idiom (assignment to a list of targets)
> as we've been talking about for the last few posts. We've had examples
> with four targets, three targets, two targets and zero targets. This is
> an example with one target.
>
> [a] = iterable
>
> requires that the right-hand side be iterable, and after unpacking it
> must contain exactly one item, to match the one assignment target given
> on the left.
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.
More information about the Python-ideas
mailing list