[Python-ideas] Spelling of Assignment Expressions PEP 572 (was post #4)
Steven D'Aprano
steve at pearwood.info
Mon Apr 16 11:54:34 EDT 2018
On Mon, Apr 16, 2018 at 06:16:46AM +1000, Chris Angelico wrote:
[...]
> >> >>> 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]
> >
> >
> > I don't know why you would write that instead of:
> >
> > items = [None]*10
> > for i in range(3):
> > items[i] = input("> ")
> >
> >
> > or even for that matter:
> >
> > items = [input("> ") for i in range(3)] + [None]*7
> >
> >
> > but whatever floats your boat. (Python isn't just not Java. It's also
> > not C *wink*)
>
> You and Kirill have both fallen into the trap of taking the example
> too far. By completely rewriting it, you destroy its value as an
> example. Write me a better example of a complex target if you like,
> but the question is about how you feel about complex assignment
> targets, NOT how you go about creating a particular list in memory.
> That part is utterly irrelevant.
Chris, I must admit that I'm utterly perplexed at this. Your example is
as far as from a complex assignment target as you can possibly get. It's
a simple name!
i := i + 1
The target is just "i", a name.
The point I was making is that your example is not a good showcase for
this suggested functionality. Your code violates DRY, repeating the
exact same line three times. It ought to be put in a loop, and once put
in a loop, the justification for needing assignment-expression
disappears.
But having said that, I did respond to your question and swapping the
order around:
items[i + 1 -> i] = input("> ")
It's still not a "complex target", the target is still just a plain ol'
name, but it is precisely equivalent to your example.
And then I went further and re-wrote your example to use a genuinely
complex target, which I won't repeat here.
> >> Are you as happy with that sort of complex
> >> expression coming after 'as' or '->'?
> >
> > Sure. Ignoring the output of the calls to input():
>
> The calls to input were in a while loop's header for a reason.
> Ignoring them is ignoring the point of assignment expressions.
What while loop? Your example has no while loop.
But regardless, we don't need to care about the *output* (i.e. your
keypresses echoed to stdout) when looking at the code sample.
--
Steve
More information about the Python-ideas
mailing list