More baby squeaking - iterators in a class

Bulba! bulba at
Thu Dec 30 18:52:36 CET 2004

Hello Mr Everyone,


"Define a __iter__() method which returns an object with a next()
method. If the class defines next(), then __iter__() can just return

The thing is, I tried to define __iter__() directly without explicit 
defining next (after all, the conclusion from this passage should
be that it's possible).

class R:
	def __init__(self, d):
	def __iter__(self):
		if self.i == 0:
			raise StopIteration
		self.i -= 1
		return self.d[self.i]

>>> s=R('spam')

>>> dir(s)
['__doc__', '__init__', '__iter__', '__module__', 'd', 'i']

Apparently no, there is no next() method. Let's see
if iterator works:

>>> s.__iter__()
>>> s.__iter__()
>>> s.__iter__()
>>> s.__iter__()
>>> s.__iter__()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 7, in __iter__

OK, this part works. But this:

>>> s=R('spam')
>>> for i in s:
	print i
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: __iter__ returned non-iterator of type 'str'

So which is it? Does next() method HAS to be defined
explicitly? That's what Wikipedia says:

"Any user defined class can support standard iteration (either
implicit or explicit) by defining an __iter__() method which creates
an iterator object. The iterator object then needs to define both an
__iter__() method as well as a next() method."

It's a man's life in a Python Programming Association.

More information about the Python-list mailing list