Extension of while syntax

Nelson Crosby nc at sourcecomb.com
Thu Dec 11 21:21:46 EST 2014


I was thinking a bit about the following pattern:

value = get_some_value()
while value in undesired_values:
    value = get_some_value()

I've always hated code that looks like this. Partly due to the repetition, but partly also due to the fact that without being able to immediately recognise this pattern, it isn't very readable.

Python already has one-line syntaxes (e.g. list comprehensions), I was wondering what people thought about a similar thing with while. It might look something like:

value = get_some_value() while value in undesired_values()

Perhaps not this exact syntax though, as the parser might try to do `value = (get_some_value() while...)` instead of `(value = get_some_value) while...`.

Other languages have features which allow something to look slightly less like this pattern, e.g. Java:

SomeType value;
while ((/* The assignment */ value = getSomeValue()) /* Compare */ == undesired_value) {}

Granted, this isn't exactly tidy, but it's a little more DRY and, IMO, preferable.

What are other's thoughts on this?



More information about the Python-list mailing list