Extension of while syntax

Chris Angelico rosuav at gmail.com
Thu Dec 11 21:38:42 EST 2014


On Fri, Dec 12, 2014 at 1:21 PM, Nelson Crosby <nc at sourcecomb.com> wrote:
> 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:

You could deduplicate it by shifting the condition:

while True:
    value = get_some_value()
    if value not in undesired_values: break

But I'm not sure how common this idiom actually is. Usually I'd modify
it, maybe with an iteration limit, or possibly some kind of prompt to
the human. Do you really have this perfectly pure form?

You could rework it to use filter(). I'm not sure that this is in any
way better code, but it is different...

>>> def get_some_value():
    return int(input("Enter a value: "))
>>> undesired_values = {1, 2, 3}
>>> next(filter(lambda x: x not in undesired_values, iter(get_some_value, object())))
Enter a value: 3
Enter a value: 1
Enter a value: 2
Enter a value: 1
Enter a value: 3
Enter a value: 1
Enter a value: 2
Enter a value: 7
7
>>>

Look, ma! No duplication!

ChrisA



More information about the Python-list mailing list