is parameter an iterable?

Alex Martelli aleax at mail.comcast.net
Tue Nov 15 19:04:51 EST 2005


Roy Smith <roy at panix.com> wrote:
   ...
> 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 not hard...:

try:
    _it = iter(whatever)
except TypeError:
    print 'non-iterable'
else:
    for i in _it: # etc, etc

Alex



More information about the Python-list mailing list