How to test if object is sequence, or iterable?

Nick Vatamaniuc vatamane at gmail.com
Sat Jul 22 17:40:45 EDT 2006


Tim,

An object is iterable if it implements the iterator protocol. 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__')

You are correct in the fact that you check if an object is iterable
rather than using isinstance to check if it is of a partucular type.
You are doing things 'the pythonic way' ;)

Nick Vatamaniuc


Tim N. van der Leeuw wrote:
> 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)
> 
> Regards,
> 
> --Tim




More information about the Python-list mailing list