Syntactic sugar for assignment statements: one value to multiple targets?
gc1223 at gmail.com
Wed Aug 17 12:33:58 CEST 2011
On Aug 17, 5:45 am, Chris Angelico <ros... at gmail.com> wrote:
> > Right. Call the proposed syntax the "instantiate separately for each
> > target" operator.
> It might just
> as easily be some other function call; for instance:
Hm--that's interesting! OK, call it the "evaluate separately for each
Same benefits in this use case; if I realize that the file only has
two header lines, I can just change
head1, head2, head3 = *file.readline()
head1, head2 = *file.readline()
without needing to keep a RHS like = [file.readline() for _ in
range(3)] in lockstep with the number of variables I'm assigning.
Presumably this syntax should be disallowed, as a grammatical matter,
when there's a starred target (per PEP 3132/language reference 6.2).
head, *body, tail = *file.readline()
is disallowed, since it is (by definition) simply sugar for
head = file.readline()
*body = file.readline()
tail = file.readline()
*body = file.readline() is disallowed (see PEP 3132). (Here, of
course, you'd just want head, *body, tail = file.readlines(), which is
perfectly good code.)
Off-topic, but the *target syntax already gets into similar territory,
a, *b, c = itertools.count()
crashes with a MemoryError--but what else could it do? Ruling out such
infinite-assignment statements on a grammatical basis would require
solving the halting problem through static analysis, which might be a
bit inefficient :P
More information about the Python-list