is parameter an iterable?

Carl Friedrich Bolz cfbolz at gmx.de
Tue Nov 15 14:46:29 EST 2005


Hi!

py wrote:
> Dan Sommers wrote:
> 
>>Just do it.  If one of foo's callers passes in a non-iterable, foo will
>>raise an exception, and you'll catch it during testing
> 
> 
> That's exactly what I don't want.  I don't want an exception, instead I
> want to check to see if it's an iterable....if it is continue, if not
> return an error code.  I can't catch it during testing since this is
> going to be used by other people.

Note that using error codes is usually quite "unpythonic", the way to 
signal that something is exceptional (not necessarily wrong) is, well, 
an exception.

Anyway, one way to solve this is the following:

def foo(input_val):
     try:
         iterator = iter(input_val)
     except TypeError:
         # do non-iterable stuff
     else:
         for val in iterator:
             # do loop stuff

Cheers,

Carl Friedrich Bolz




More information about the Python-list mailing list