[capi-sig] How do I make a subclass of a C class iterable?

Jason Baker amnorvend at gmail.com
Sat Oct 30 20:14:45 CEST 2010

My package has an optional C extension.  Here's an abbreviated version of
what I have:

    from pysistence._persistent_list import PList as BasePList
except ImportError:
    class BasePList(object):
        __slots__ = ['_first', '_rest']
        def __init__(self, first, rest=None):
            self._first = first
            self._rest = rest
        def cons(self, item):
            return self.__class__(item, self)

class PList(BasePList):
    def __iter__(self):

So what I'm basically doing is subclassing a base class (which is defined in
Python or C) and adding an __iter__ method.  This works fine if I don't use
the C extension, but if I do use it I get the following error:

Traceback (most recent call last):
line 297, in main
    x = t.timeit(number)
line 193, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 11, in inner
    for i in iter(datalist):
TypeError: 'pysistence.persistent_list.PList' object is not iterable

Is there a way to define the __iter__ method in Python, or am I going to
have to do that in C?

More information about the capi-sig mailing list