string: __iter__()?

John Roth JohnRoth1 at
Wed Oct 4 17:11:38 CEST 2006

mrquantum wrote:
> Hello!
> Just for curiosity i'd like to know why strings don't support the
> iteration protocoll!? Is there some deeper reason for this?
> >>> hasattr('SomeString', '__iter__')
> False
> In Python 2.5 it's actually simple to obtain one:
> >>> myIter = (c for c in 'SomeString')
> >>>
> 'S'
> Thanks for info!
> Chris

The iter() builtin creates an iterator for any
object that obeys the sequence protocol.
Since strings obey the sequence protocol there
is no real advantage to adding yet another
protocol to an already very fat object.

This  does, however, mean that testing
for the presence of __iter__ is incomplete;
one also has to test for __getattr__ if the
object doesn't have an __Iter__ method.

Depending on  your program logic, it
may be easier to just use iter() and
handle the exception if it fails.

See PEP 234 for a discussion of the
reasons for doing it this way.

John Roth

More information about the Python-list mailing list