JohnRoth1 at jhrothjr.com
Wed Oct 4 17:11:38 CEST 2006
> 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__')
> In Python 2.5 it's actually simple to obtain one:
> >>> myIter = (c for c in 'SomeString')
> >>> myIter.next()
> Thanks for info!
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.
More information about the Python-list