Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython - use of "from" keyword in for loop

Tags:

python

cython

I was recently reading some source code from sklearn's BallTree class, which is written in Cython, and I came across some bizarre syntax in a for loop:

for j from 0 <= j < n_features:
    centroid[j] += this_pt[j]

After some looking around, I'm unable to find any documentation for the use of the from keyword in a for loop. In fact, this answer explicitly states that the only use of from in Python is in the import_from clause.

Though it reads strangely, my interpretation of the line is essentially:

for j in range(n_features):
    ...

...which adheres to the condition that j start with 0 and remain less than n_features. What exactly is the advantage of the strange syntax, and is it doing something differently than I expect?

like image 422
TayTay Avatar asked Mar 14 '23 07:03

TayTay


2 Answers

It is a legacy form.

For backwards compatibility to Pyrex, Cython also supports a more verbose form of for-loop which you might find in legacy code:

for i from 0 <= i < n:

Taken from Cython docs

like image 39
Roman Kh Avatar answered Mar 23 '23 01:03

Roman Kh


It's an oldie that was retained for compatibility with pyrex (a cython predecessor).

for i from 0 <= i < n:

is equivalent to

for i in range(n):

You should note that it is deprecated.

like image 131
Ami Tavory Avatar answered Mar 23 '23 00:03

Ami Tavory