is_iterable function.

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Wed Jul 25 15:11:34 EDT 2007


On Wed, 25 Jul 2007 11:58:40 -0700, danmcleran at yahoo.com wrote:

> You can use the built-in dir() function to determine whether or not
> the __iter__ method exists:

Doesn't work:

In [58]: is_iterable('hello')
Out[58]: False

But strings *are* iterable.

And just calling `iter()` doesn't work either:

In [72]: class A:
   ....:     def __getitem__(self, key):
   ....:         if key == 42:
   ....:             return 'answer'
   ....:         raise KeyError
   ....:

In [73]: iter(A())
Out[73]: <iterator object at 0xb7829b2c>

In [74]: a = iter(A())

In [75]: a.next()
---------------------------------------------------------------------------
<type 'exceptions.KeyError'>            Traceback (most recent call last)

/home/bj/<ipython console> in <module>()

/home/bj/<ipython console> in __getitem__(self, key)

<type 'exceptions.KeyError'>:


So there's no reliable way to test for "iterables" other than actually
iterate over the object.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list