[Cython] can we deprecate for-from loops?
robertwb at gmail.com
Tue Oct 13 00:51:22 EDT 2015
On Mon, Oct 12, 2015 at 11:40 AM, Josh Ayers <josh at ayers.pw> wrote:
> When the step size is a variable, the range statement falls back to a
> Python for loop since the direction of the loop is unknown. The "i from
> a <= i < b by c" syntax specifies the direction, so it is turned into a
> C for loop. The difference is performance could be substantial.
> This produces a Python for loop:
> def python_loop(Py_ssize_t a, Py_ssize_t b, Py_ssize_t c):
> cdef Py_ssize_t i
> for i in range(a, b, c):
I thought we had fixed that... apparently not. Doable (e.g. multiply
a, b, c, and then i by the sign of c, checking for 0 of course) but
> This produces a C for loop:
> def c_loop(Py_ssize_t a, Py_ssize_t b, Py_ssize_t c):
> cdef Py_ssize_t i
> for i from a <= i < b by c:
Ah, there is a slight semantic difference: this will be an infinite
for...from loop if c is not positive (and a < b), but an empty
for...in loop for range.
However, there's another catch: for...from can be used with
non-integral values (doubles, pointers, ...) Unless we wanted to
introduce, say, something like cython.crange it may be more painful to
force users to express that as while loops.
I was hoping to get rid of it, but now I'm not sure it'd be that easy.
> On Mon, Oct 12, 2015, at 08:37 AM, Robert Bradshaw wrote:
>> On Sun, Oct 11, 2015 at 3:31 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>
>> > Stefan Behnel wrote:
>> >> Hi!
>> >> The syntax construct "for i from 0 <= i < 10" has been silently outdated
>> >> for years. Can we start issuing a warning that normal range() loops are
>> >> preferred?
>> > I'd be in favour of replacing it with just 'for 0 <= i < 10',
>> > but -1 on removing it altogether.
>> > I introduced it in Pyrex for a reason -- to clearly express
>> > iterations over ranges of integers with arbitrary combinations
>> > of open/closed endpoints,
>> I agree that it expresses intent clearer than the range(...) construct.
>> > for use in conjunction with C code.
>> > I believe that reason is still valid.
>> I'm not sure why "in conjunction with C code" makes any difference to
>> the argument, now that the basic range loop produces the same code in
>> Cython. Put another way, does its clarity merit a PEP to introduce
>> this syntax into Python? If not, it's hard to justify in Cython given
>> that it is a fully redundant addition to the language.
>> - Robert
>> cython-devel mailing list
>> cython-devel at python.org
> cython-devel mailing list
> cython-devel at python.org
More information about the cython-devel