is parameter an iterable?

Steven D'Aprano steve at
Wed Nov 16 22:35:19 CET 2005

On Wed, 16 Nov 2005 09:06:01 -0500, Rick Wotnaz wrote:

[cutting to the important bit]
>>     except TypeError, msg:
>>         if msg == "iteration over non-sequence":
>>             # handle non-iterable case

> Does this in fact work on your system? On mine (2.4.1 (#65, Mar 30 
> 2005, 09:13:57) [MSC v.1310 32 bit (Intel)]), it doesn't seem to.

Dammit, that will teach me not to test my code before posting.

No it doesn't: msg is an object of type exceptions.TypeError.

The easy fix is to just coerce it to a string:

if str(msg) == "iteration over non-sequence":

which *does* work on my system. But perhaps a better way is to do this:

# Create an instance of the exception you expect:
    for i in 0:
except TypeError, ITER_OVER_NON_SEQ:
# Now run your code...
    ...blah blah blah...
except TypeError, msg
    if str(msg) == str(ITER_OVER_NON_SEQ):
        ...blah blah blah... 

This means we're no longer assuming what the error message will be,
which makes our code a lot more future-proof and implementation-proof: if
some version of Python changes the error string from "iteration over
non-sequence" to something else, the code should continue to work


More information about the Python-list mailing list