is parameter an iterable?

Roy Smith roy at panix.com
Wed Nov 16 09:56:00 EST 2005


In article <Xns97105D1B0A505reederz at 63.223.7.253>,
 Rick Wotnaz <desparn at wtf.com> wrote:

> Steven D'Aprano <steve at REMOVETHIScyber.com.au> wrote in
> news:pan.2005.11.15.22.57.58.855137 at REMOVETHIScyber.com.au: 
> 
> > def foo(inputVal):
> >     try:
> >         for val in inputVal:
> >             # do stuff
> >     except TypeError, msg:
> >         if msg == "iteration over non-sequence":
> >             # handle non-iterable case
> >         else:
> >             # some other TypeError is a bug, so re-raise the
> >             exception raise
> 
> 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. I 
> tried 
>     	if msg.find("iteration over non-sequence") >= 0:
> ... but I got a traceback, and 
> AttributeError: TypeError instance has no attribute 'find'
> ... which leads me to belive that 'msg' is not type(str). It can be 
> coerced (str(msg).find works as expected). But what exactly is msg? 
> It appears to be of <type 'instance'>, and does not test equal to a 
> string. This is not the least surprise to me.

It's an easy experiment to do:

-------------------
Roy-Smiths-Computer:play$ cat ex.py
#!/usr/bin/env python

try:
    1 + "foo"
except TypeError, msg:
    print type(msg)
    print msg
    print repr(msg)
    print dir(msg)
Roy-Smiths-Computer:play$ py ex.py
<type 'instance'>
unsupported operand type(s) for +: 'int' and 'str'
<exceptions.TypeError instance at 0x36d968>
['__doc__', '__getitem__', '__init__', '__module__', '__str__', 'args']
---------------------



More information about the Python-list mailing list