reader = module.Class(file_or_similar_object, option1, option2, ...)
for record in reader:
process(record)
As "yield" is not yet available in Cython, I used the __iter__ method as
in the following minimal code:
=== titer.pyx ===
cdef class Titer(object):
cdef object guff
cdef object pos
def __init__(self, object guff):
self.guff = guff
self.pos = 0
def __iter__(self):
return self
cpdef next(self):
if self.pos >= len(self.guff):
raise StopIteration
x = self.guff[self.pos]
self.pos += 1
return x
=== end of titer.pyx ===
With all the c[p]def bits stripped out, this works happily with both
Python and Cython on simple tests like:
python -c"import titer;x=titer.Titer([9,8,7]);print list(x)"
(Windows XP SP2, Python 2.6.4, Cython 0.12.1)
Unfortunately with the cdef-ed class, the code above produces this message:
TypeError: iter() returned non-iterator of type 'titer.Titer'
My motive for wanting a c[p]def class is that there are several
attributes (like self.pos) that are heavily used in loops in the "next"
method and would benefit from being c[p]def-ed.
Is there any simple adjustment to the above code that would make its
iter() return an acceptable iterator? I had tried "cpdef class ..." with
0.11 but (a) this didn't do what I wanted and (b) is now forbidden by
0.12.1.
Thanks in advance,
John
The right name for this method in Cython is "__next__". Note that it needs
to be defined as a plain "def" method.
Stefan
Thanks very much for the prompt reply, Stefan. I can't advance a
plausible reason other than innate silliness for not being able to find
that in the docs for myself -- sorry for the noise.
Cheers,
John