[Cython] Fix for #196 (for loop bug)
Dag Sverre Seljebotn
dagss at student.matnat.uio.no
Fri Jan 30 14:23:02 CET 2009
Magnus Lie Hetland wrote:
> On Jan 30, 2009, at 14:03, Magnus Lie Hetland wrote:
>
>
>> for i in range(0,10,2): pass
>> for j in range(0,10,getstep()): pass
>>
>> print i, j
>> # (10, 8)
>>
>
>
> Ahm. I guess the explanation here was, in fact, quite obvious from the
> fact that the code was too hairy for me to see the bug: Unless I'm
> mistaken, the version with the function call isn't optimized and
> hence, its behavior is in line with Python semantics.
>
> Then again, if getstep is cdef-ed to return an int, why *isn't* this
> optimized to a for-from-loop? (And if it should be, the local variable
> issue that Dag Sverre mentioned is again relevant.)
>
Ah. Line 115 in Optimize.py: Apparently the step direction cannot be
determined, which is why it isn't optimized unless it is a compile-time
constant. So the expressions will only be constant and your fix is OK
(except that the flag is needed to preserve for-from behaviour).
(One could get around this by a more elaborate temporary variable
shuffling prior to the loop with a runtime if-test (i.e. if step is
negative, exchange bounds), but that's digressing way beyond a simple
bugfix. Shows that it is really important with a regression test here
though in case that is done in the future -- i.e. print something from
the getstep() function so that the side-effects can be traced in the
doctest)
Dag Sverre
More information about the Cython-dev
mailing list