How to test if object is sequence, or iterable?

Tim N. van der Leeuw tim.leeuwvander at nl.unisys.com
Sat Jul 22 15:04:08 EDT 2006


Bruno Desthuilliers wrote:
> Tim N. van der Leeuw a écrit :
> > Hi,
> >
> > I'd like to know if there's a way to check if an object is a sequence,
> > or an iterable. Something like issequence() or isiterable().
> >
> > Does something like that exist? (Something which, in case of iterable,
> > doesn't consume the first element of the iterable)
>
> isiterable = lambda obj: isinstance(obj, basestring) \
>                           or getattr(obj, '__iter__', False)
>
>
> Should cover most cases.

Yes, that seems to cover all cases I can think of, indeed. Funny
though, that string objects do not have an '__iter__' method, but are
still iterable... But it will make most of my use-cases easier: Often I
want to iterate over something, if it's an iterable, except when it's a
string.


Thanks,

--Tim




More information about the Python-list mailing list