seeking deeper (language theory) reason behind Python design choice

Chris Angelico rosuav at gmail.com
Fri May 11 09:38:56 EDT 2018


On Fri, May 11, 2018 at 11:28 PM, Ian Kelly <ian.g.kelly at gmail.com> wrote:
> You can get rid of the while loop:
>
> for x in iter(get_item, None):
>     process(x)
>
> The reason I suggested the function I did is because the x in that
> case can't reasonably be turned into an iterator because the logic
> depends on the loop body. You can't encapsulate the iteration logic
> without having side-effects in the iteration or duplicating code.

That's actually equivalent to:

while (x := get_item()) != None:
    process(x)

That's not often going to be what you want. If the function is
guaranteed to return None, you should be using "is not None", and if
it's simply returning something falsey, you should be checking
truthiness. Once again, this is shoe-horning the available mechanics
into tasks that aren't quite what they're designed for; they're "close
enough" for a lot of cases, but not really correct.

ChrisA



More information about the Python-list mailing list