[Python-ideas] Spelling of Assignment Expressions PEP 572 (was post #4)
Chris Angelico
rosuav at gmail.com
Sun Apr 15 08:21:02 EDT 2018
On Sun, Apr 15, 2018 at 7:19 PM, Kirill Balunov <kirillbalunov at gmail.com> wrote:
>> === Expression first, 'as' keyword ===
>>
>> while (read_next_item() as value) is not None:
>> ...
>>
>> Pros:
>>
>> * typically reads nicely as pseudocode
>> * "as" is already associated with namebinding operations
>>
>
> I understand that this list is subjective. But as for me it will be huge PRO
> that the expression comes first.
I don't think we're ever going to unify everyone on an arbitrary
question of "expression first" or "name first". But to all the
"expression first" people, a question: what if the target is not just
a simple name?
while (read_next_item() -> items[i + 1 -> i]) is not None:
print("%d/%d..." % (i, len(items)), end="\r")
Does this make sense? With the target coming first, it perfectly
parallels the existing form of assignment:
>>> items = [None] * 10
>>> i = -1
>>> i, items[i] = i+1, input("> ")
> asdf
>>> i, items[i] = i+1, input("> ")
> qwer
>>> i, items[i] = i+1, input("> ")
> zxcv
>>> items
['asdf', 'qwer', 'zxcv', None, None, None, None, None, None, None]
The unpacking syntax is a bit messy, but with expression assignment,
we can do this:
>>> items = [None] * 10
>>> i = -1
>>> items[i := i + 1] = input("> ")
> asdf
>>> items[i := i + 1] = input("> ")
> qwer
>>> items[i := i + 1] = input("> ")
> zxcv
>>>
>>> items
['asdf', 'qwer', 'zxcv', None, None, None, None, None, None, None]
Okay, it's not quite as simple as C's "items[i++]" (since you have to
start i off at negative one so you can pre-increment), but it's still
logical and sane. Are you as happy with that sort of complex
expression coming after 'as' or '->'?
Not a rhetorical question. I'm genuinely curious as to whether people
are expecting "expression -> NAME" or "expression -> TARGET", where
TARGET can be any valid assignment target.
ChrisA
More information about the Python-ideas
mailing list