Critique of first python code

George Sakkis george.sakkis at gmail.com
Sun Feb 17 11:07:22 EST 2008


On Feb 17, 10:17 am, Matthew Marshall <matt... at matthewmarshall.org>
wrote:
> Dan Bishop wrote:
> > I will say, however, that hasattr(item, '__iter__') isn't a perfect
> > way of checking whether an object is iterable: Objects that just
> > define __getitem__ are iterable too (e.g., UserList).
>
> Speaking of which, what *is* the best way to check if an object is
> iterable?
>
> I always wrap iter(item) in a try/except block,

Yes, that's the most foolproof way.

> but is there an
> isiterable() function somewhere?

Not AFAIK, but if I had to write one, I would use

isiterable = lambda x: hasattr(x, '__iter__') or
                       hasattr(x, '__getitem__')


In Python 3 it will be isinstance(x, Iterable).

George



More information about the Python-list mailing list