[Python-ideas] Inline assignments using "given" clauses
Clint Hepner
clint.hepner at gmail.com
Fri May 11 10:06:19 EDT 2018
> On 2018 May 11 , at 7:37 a, Rhodri James <rhodri at kynesim.co.uk> wrote:
>
> On 11/05/18 11:14, Jacco van Dorp wrote:
>> 2018-05-11 11:56 GMT+02:00 João Santos <jmcs at jsantos.eu>:
>>> Optimizing syntax for space makes sense for "mathematical" notation since
>>> it's commonly written by hand, but putting space above readability in a
>>> programming language design feels like a skewmorphism.
>> You are assuming "given" to improve readability, where I stated ":= is
>> perfectly clear ", at least in my opinion. Therefore, since clarity is
>> already achieved, the rest is clutter that reduces readability.
>
> I respectfully disagree with your opinion (i.e. you're wrong :-)
>
> Consider:
>
> while (cmd := get_command()).token != CMD_QUIT:
> cmd.do_something()
>
> vs:
>
> while cmd.token != CMD_QUIT given cmd = get_command():
> cmd.do_something()
>
>
> I find I write code like this[*] a fair bit, since my major use for Python is to write remote monitors for embedded kit, so it's pretty much a real world example. I don't find the first version using ":=" to be perfectly clear, in fact I think it's rather ugly. That may be partly the same reaction that many of us had to the asymmetry of assignment expressions in (over-)complicated comprehensions. The second version using "given" reads much more naturally to the mathematician in me, and not too badly to my English half either.
I would write this using a for loop and the two-argument form of iter:
for cmd in iter(get_command, ''):
if cmd.token == CMD_QUIT:
break
cmd.do_something()
or
from itertools import take while
for cmd in takewhile(lambda x: x.token != CMD_QUIT, iter(get_command, '')):
cmd.do_something()
Depending on what get_command actually returns, you might be able to construct a valid sentinel that
doesn't require an explicit test of cmd.token.
(This reminds that I wish ``iter`` could take a predicate instead of a sentinel as its second argument. Then
you could just write
for cmd in iter(get_command, lambda x: x.token == CMD_QUIT):
cmd.do_something()
)
--
Clint
More information about the Python-ideas
mailing list