[Python-ideas] if in for-loop statement
Jelle Zijlstra
jelle.zijlstra at gmail.com
Thu Feb 23 09:51:12 EST 2017
2017-02-23 5:37 GMT-08:00 Henk-Jaap Wagenaar <wagenaarhenkjaap at gmail.com>:
>
> Hi all,
>
> Often I have typed something like
>
> for x in range(100) if is_prime(x):
> # do things with x
>
> to find that this does not work, instead resorting to:
>
> for x in range(100):
> if is_prime(x):
> # do things with x
>
> or
>
> for x in range(100):
> if not is_prime(x):
> continue
> # do things with x
>
> Other solutions to another case of this 'problem' are discussed has been discussed on StackOverflow (http://stackoverflow.com/questions/6981717/pythonic-way-to-combine-for-loop-and-if-statement) where it is suggested one uses a generator expression before the loop. None of these solutions seem very Pythonic to me.
>
> I appreciate there is a cost associated with changing the language syntax, and I do not understand all the finer details of the inner workings involved with the Python language development, however in my limited understanding in it would be:
> - fully backwards compatible,
> - require one to change "expression_list" to "or_test [comp_iter]" in the syntax of the for statement (if I got it right).
> - it would mean there is a Pythonic solution to a current 'problem' that does not have one.
>
> A few problems I foresee:
> - One wants for loops to bleed their target_list (that is the point normally), so this is different from generators,
> - This allows for nesting of generators, like in a generator expression which might be hard to implement?
>
I think it might also be difficult to parse. Python currently supports
this syntax:
In [8]: for x in [1, 2] if True else [1, 2, 3]:
...: print(x)
...:
1
2
I'm not sure the parser could distinguish this structure from the one
you propose (which would have a very different meaning) without making
it significantly more complicated. Changes that make the parser more
complicated than LL(1) have been consistently rejected in the past;
see https://www.python.org/dev/peps/pep-3099/.
>
> Note that this has been suggested before at least once (https://mail.python.org/pipermail/python-dev/2007-November/075257.html), and that thread itself suggests it has been suggested before and shutdown by Guido (though no source is given for this).
>
> All the best,
>
> Henk-Jaap Wagenaar
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list