Newbie - How to iterate list or scalar ?

Bruno Desthuilliers onurb at xiludom.gro
Tue Aug 8 13:59:47 EDT 2006


Andy Dingley wrote:
> Bruno Desthuilliers wrote:
> 
>> there's really no reason to
>> assume it should be a list - any iterable could - and IMHO should - be
>> accepted... expect of course for strings (royal PITA case, duh).
> 
> 
>> 2/ test for pluginVersionsNeeded.__iter__ (an attribute of most
>> iterables except strings...):
> 
> strings don't have __iter__ ?!?!

No. Should they ?-)

> I'm never going to get my head round this language   8-(

Hmmm.... While simple to get started with, Python is *not* a 'simple'
language. There's a price to pay for it's flexibility, and this price is
named "complexity". While one doesn't necessary needs to deal with it,
this complexity shows as soon as you start to dig deeper into "advanced"
features.


FWIW, if I judge on source code I've seen so far, the canonical way to
distinguish a string from another sequence type or iterable is still to
use isinstance(obj, basestring), and I don't know if I should have
mentionned the hasattr(obj, '__iter__') hack at all.


> I can understand strings and tuples being iterable, if you take a
> sufficiently first-class view of things, but why shouldn't everything
> "that is iterable" support the function that makes iteration work?

Actually, __iter__ is not needed to allow for loops on an object if the
object defines __getitem__ so that it supports numeric indexing:

class MySequence(object):
    def __init__(self):
        self._data = range(3)
    def __getitem__(self, key):
        return self._data[key]

>>> m = MySequence()
>>> for x in m: print x
...
0
1
2

FWIW, the iterator protocol appeared with Python 2.2. Before this
version, the above solution was the only one that allowed iteration over
a container type.

Now  if you wonder why string, unicode and buffer don't have __iter__
while other sequence types have it, ask your favourite Python guru (and
please keep me informed !-). Fact is that Python is not exactly a
newborn language (first release was around 1990 IIRC), and it has
greatly evolved over the year. The BDFL being very conservative, great
cares have been taken to ensure compatibility with older versions - with
the side effect that there are lots of stuff that now looks like warts
or inconsistencies. The 3K release is supposed to be the big cleanup,
but until then, we'll have to live with all the compat stuff.

HTH



More information about the Python-list mailing list