How to test if object is sequence, or iterable?

Terry Reedy tjreedy at udel.edu
Sat Jul 22 20:49:01 EDT 2006


"Nick Vatamaniuc" <vatamane at gmail.com> wrote in message 
news:1153604445.246639.81270 at h48g2000cwc.googlegroups.com...
> Tim,
>
> An object is iterable if it implements the iterator protocol

There are presently two iterator protocols.  The old one will be likely be 
dropped in 3.0 (currently being discussed).

>. A good
> enough check to see if it does is to check for the presense of the
> __iter__() method. The way to do it is:
> hasattr(object,'__iter__')

Sorry, this check for the newer and nicer protocol but not the older one.

>>> hasattr('abc', '__iter__')
False

This may change in 2.6.  The defacto *version-independent* way to determine 
iterability is to call iter(ob).  If it returns an iterator, you can 
iterate; if it raises TypeError, you cannot.  Any it should be patched as 
necessary by the developers to continue doing the right thing in future 
versions.

Terry Jan Reedy






More information about the Python-list mailing list