[Python-Dev] PEP 572: Assignment Expressions (original) (raw)

Chris Angelico rosuav at gmail.com
Fri Apr 20 02:46:05 EDT 2018


On Fri, Apr 20, 2018 at 1:30 PM, Stephen J. Turnbull <turnbull.stephen.fw at u.tsukuba.ac.jp> wrote:

Christoph Groth writes:

> Wouldn't it be a pity not to liberate assignments from their boring > statement existence? Maybe not. While it would be nice to solve the loop-and-a-half "problem" and the loop variable initialization "problem" (not everyone agrees these are even problems, especially now that we have comprehensions and generator expressions), as a matter of taste I like the fact that this particular class of side effects is given weighty statement syntax rather than more lightweight expression syntax. That is, I find statement syntax more readable.

If you've read the PEP, you'll see that it encourages the use of assignment statements whereever possible. If statement syntax is generally more readable, by all means, use it. That doesn't mean there aren't situations where the expression syntax is FAR more readable.

Tell me, is this "more readable" than a loop with an actual condition in it?

def sqrt(n): guess, nextguess = 1, n while True: if math.isclose(guess, nextguess): return guess guess = nextguess nextguess = n / guess

Readable doesn't mean "corresponds closely to its disassembly", despite the way many people throw the word around. It also doesn't mean "code I like", as opposed to "code I don't like". The words for those concepts are "strongly typed" and "dynamically typed", as have been demonstrated through MANY online discussions. (But I digress.) Readable code is code which expresses an algorithm, expresses the programmer's intent. It adequately demonstrates something at a higher abstraction level. Does the algorithm demonstrated here include an infinite loop? No? Then it shouldn't have "while True:" in it.

Now, this is a pretty obvious example. I deliberately wrote it so you could simply lift the condition straight into the while header. And I hope that everyone here agrees that this would be an improvement:

def sqrt(n): guess, nextguess = 1, n while not math.isclose(guess, nextguess): guess = nextguess nextguess = n / guess return guess

But what if the condition were more complicated?

def read_document(file): doc = "" while (token := file.get_next_token()) != "END": doc += token return doc

The loop condition is "while the token is not END", or "while get_next_token() doesn't return END", depending on your point of view. Is it "more readable" to put that condition into the while header, or to use an infinite loop and a break statement, or to duplicate a line of code before the loop and at the bottom of the loop? Which one best expresses the programmer's intention?

ChrisA



More information about the Python-Dev mailing list