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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With