[Cython] For loop bug?

Magnus Lie Hetland magnus at hetland.org
Wed Jan 28 14:53:31 CET 2009


This is definitely a corner case -- and it may be an intentional  
incompatibility with Python (and, for all I know, I may have missed  
some documentation on it somewhere), but ... here goes:

After a for-loop in Python, the index variable will retain its last  
value. E.g.:

   for i in range(10): pass
   print i
   # Prints out 9

In Cython, however, standard C-semantics are used for the counting for- 
loops, so the index variable is incremented one step beyond the value  
it had in the last iteration.

I just wrote some code where this was an issue. It's easy to fix, of  
course (just use a statement like "i -= 1" or something) -- but it  
does mean an incompatibility between Python and Cython...

I realise that adding an "i -= 1" statement in general, as a blanket  
solution, would be rather wasteful (as most code doesn't rely on this  
property). Perhaps it would be possible to do some analysis on whether  
the index variable is used without modification later? (I realise that  
this is intractable in the general case, but perhaps there could be  
some well-defined rules?)

- M

-- 
Magnus Lie Hetland
http://hetland.org




More information about the Cython-dev mailing list