On Fri, Jun 18, 2021 at 10:10:33PM +0900, Stephen J. Turnbull wrote:
> Pretty clearly the * means ...
>
> It did take me a bit of thought to come to Ben's intended
> interpretation ...
So perhaps not actually that clear then? *wink*
In hindsight, after realising what Ben's intention was (at least we
assume that is what he was thinking of) it does seem like a reasonable
way of unpacking multiple items into a list or set comprehension at
once.
I don't think that this is something that we could say was "intuitively
obvious" to somebody who is neither Dutch not experienced with Python,
but I think it is retroactively obvious once explained.
Unpacking comprehensions:
[*item for item in sequence]
{*item for item in sequence]
are syntactic sugar for something roughly equivalent to:
result = [] # or set()
for item in sequence:
for tmp in item:
result.append(tmp) # or result.add
The exact implementation could vary, e.g. by using `extend` for list
comprehensions.
That suggests a meaning for double-star unpacking in a dict
comprehension (single-star unpacking would make it a set).
{**item for item in seq}
# equivalent to:
result = {}
for item in seq:
result.update(item)
And these suggest meanings for the equivalent in generator
expressions:
(*item for item in sequence)
# equivalent to:
(tmp for item in sequence for tmp in item)
The double-star version would follow similar rules to dict.update:
(**item for item in sequence)
# equivalent to:
def gen():
for item in sequence:
if hasattr(item, 'keys'):
for k in item:
yield (k, item[k])
else:
for k, v in item:
yield (k, v)
Works for me.
--
Steve
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/P2QSA6K3T3BJRX26HR4W36447XGHNM2F/
Code of Conduct: http://python.org/psf/codeofconduct/