[Python-ideas] Fwd: Fwd: unpacking generalisations for list comprehension
Paul Moore
p.f.moore at gmail.com
Thu Oct 13 16:42:04 EDT 2016
On 13 October 2016 at 20:51, Random832 <random832 at fastmail.com> wrote:
> On Thu, Oct 13, 2016, at 15:46, Random832 wrote:
>> so, under a similar 'transformation', "*foo for foo in bar" likewise
>> becomes "def f(): for foo in bar: yield from foo"
>>
>> bar = [(1, 2), (3, 4)]
>> (*(1, 2), *(3, 4)) == == tuple(f())
>> [*(1, 2), *(3, 4)] == == list(f())
>
>
> I accidentally hit ctrl-enter while copying and pasting, causing my
> message to go out while my example was less thorough than intended and
> containing syntax errors. It was intended to read as follows:
>
> ..."*foo for foo in bar" likewise becomes
>
> def f():
> for foo in bar:
> yield from foo
>
> a, b = (1, 2), (3, 4)
> bar = [a, b]
> (*a, *b) == (1, 2, 3, 4) == tuple(f()) # tuple(*foo for foo in bar)
> [*a, *b] == [1, 2, 3, 4] == list(f()) # [*foo for foo in bar]
I remain puzzled.
Given the well-documented and understood transformation:
[fn(x) for x in lst if cond]
translates to
result = []
for x in lst:
if cond:
result.append(fn(x))
please can you explain how to modify that translation rule to
incorporate the suggested syntax?
Personally, I'm not even sure any more that I can *describe* the
suggested syntax. Where in [fn(x) for x in lst if cond] is the *
allowed? fn(*x)? *fn(x)? Only as *x with a bare variable, but no
expression? Only in certain restricted types of construct which aren't
expressions but are some variation on an unpacking construct?
We've had a lot of examples. I think it's probably time for someone to
describe the precise syntax (as BNF, like the syntax in the Python
docs at https://docs.python.org/3.6/reference/expressions.html#displays-for-lists-sets-and-dictionaries
and following sections) and semantics (as an explanation of how to
rewrite any syntactically valid display as a loop). It'll have to be
done in the end, as part of any implementation, so why not now?
Paul
More information about the Python-ideas
mailing list