is_iterable function.

Carsten Haese carsten at uniqsys.com
Wed Jul 25 15:15:26 EDT 2007


On Wed, 2007-07-25 at 11:58 -0700, danmcleran at yahoo.com wrote:
> You can use the built-in dir() function to determine whether or not
> the __iter__ method exists:
> 
> class Iterable(object):
>     def __iter__(self):
>         pass
> 
> class NotIterable(object):
>     pass
> 
> def is_iterable(thing):
>     return '__iter__' in dir(thing)
> 
> print 'list is iterable = ', is_iterable(list())
> print 'int is iterable = ', is_iterable(10)
> print 'float is iterable = ', is_iterable(1.2)
> print 'dict is iterable = ', is_iterable(dict())
> print 'Iterable is iterable = ', is_iterable(Iterable())
> print 'NotIterable is iterable = ', is_iterable(NotIterable())
> 
> Results:
> list is iterable =  True
> int is iterable =  False
> float is iterable =  False
> dict is iterable =  True
> Iterable is iterable =  True
> NotIterable is iterable =  False

Testing for __iter__ alone is not enough:

>>> class X(object):
...   def __getitem__(self,i):
...     if i<10: return i
...     else: raise IndexError, i
... 
>>> x = X()
>>> is_iterable(x)
False
>>> iter(x)
<iterator object at 0xb7f0182c>
>>> for i in x: print i
... 
0
1
2
3
4
5
6
7
8
9

No __iter__ in sight, but the object is iterable.

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list