Why is there no __iter__() for lists strings and tuples?

Parzival Herzog parz at shaw.SpamBucket.ca
Fri Dec 20 15:07:20 EST 2002


>From the Python 2.2.2 Documentation:



Section 2.2.2 states:

New in version 2.2.

Python supports a concept of iteration over containers. This is implemented
using two distinct methods; these are used to allow user-defined classes to
support iteration. Sequences, described below in more detail, always support
the iteration methods.

One method needs to be defined for container objects to provide iteration
support:


  __iter__()
  Return an iterator object. The object is required to support the iterator
protocol described below. If a container supports different types of
iteration, additional methods can be provided to specifically request
iterators for those iteration types. (An example of an object supporting
multiple forms of iteration would be a tree structure which supports both
breadth-first and depth-first traversal.) This method corresponds to the
tp_iter slot of the type structure for Python objects in the Python/C API.
Section 2.2.6 states:
There are six sequence types: strings, Unicode strings, lists, tuples,
buffers, and xrange objects.



In real life:

ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on
Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.


>>> x = 'abcdef'


>>> x.__iter__()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'str' object has no attribute '__iter__'


>>> list(x).__iter__()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute '__iter__'


>>> tuple(x).__iter__()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute '__iter__'
>>>


>>> [1,2,3].__iter()__
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'list' object has no attribute '__iter__'
>>>

So is this a bug? Are strings, lists and tuples sequences? If they are, why
is there no __iter__() attribute for them?





More information about the Python-list mailing list