is parameter an iterable?

Roy Smith roy at panix.com
Tue Nov 15 15:02:48 EST 2005


In article <1132081308.036144.13720 at g49g2000cwa.googlegroups.com>,
py <codecraig at gmail.com> wrote:
>I have function which takes an argument.  My code needs that argument
>to be an iterable (something i can loop over)...so I dont care if its a
>list, tuple, etc.

My first thought was to just write your loop inside a try block and
catch the error if it wasn't iterable, but then I noticed that you get:

TypeError: iteration over non-sequence

I was kind of hoping for a more specific exception than TypeError.
You can't tell the difference between:

try:
  for i in 5:
    print i + 1
except TypeError:
  print "non-iterable"

and

try:
  for i in ["one", "two", "three"]:
    print i + 1
except TypeError:
  print "can't add string and integer"

Unfortunately, you can't just try it in a bodyless loop to prove that
you can iterate before doing the real thing because not all iterators
are idempotent.

It's an interesting problem.



More information about the Python-list mailing list