Skip to content

Instantly share code, notes, and snippets.

@pydemo
Last active September 7, 2018 16:50
Show Gist options
  • Save pydemo/9ac8ea101e3f4fd7d628d66046b28c79 to your computer and use it in GitHub Desktop.
Save pydemo/9ac8ea101e3f4fd7d628d66046b28c79 to your computer and use it in GitHub Desktop.
Iterator support in Cython.

To make extension iterable you define iter on it.

cdef class I:

   cdef:

   list data

   int i

   def __init__(self):

   self.data = range(100)

   self.i = 0

   def __iter__(self):

   return self

   def __next__(self):

   if self.i >= len(self.data):

   raise StopIteration()

   ret = self.data[self.i]

   self.i += 1

   return ret

It can be used in for loops.

In [3]: i = I()

 

In [4]: s = 0

 

In [5]: for x in i:

  ...: s += x

  ...:

 

In [6]: s

Out[6]: 4950

Instances can be used where iterator is required.

In [15]: it = iter(I())

 

In [16]: it.next()

Out[16]: 0

 

In [17]: next(it)

Out[17]: 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment