TypeError: iter() returned non-iterator of type 'titer.Titer'

2,045 views
Skip to first unread message

John Machin

unread,
Aug 16, 2010, 1:07:10 AM8/16/10
to cython...@googlegroups.com

Problem: I would like to Cythonise a file parser module which is
intended to be used like this:

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


Stefan Behnel

unread,
Aug 16, 2010, 2:29:36 AM8/16/10
to cython...@googlegroups.com
John Machin, 16.08.2010 07:07:
> cpdef next(self):

The right name for this method in Cython is "__next__". Note that it needs
to be defined as a plain "def" method.

Stefan

John Machin

unread,
Aug 16, 2010, 6:38:05 AM8/16/10
to cython...@googlegroups.com

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

Reply all
Reply to author
Forward
0 new messages