unboundlocalerror with cgi module

Tim Hochberg tim.hochberg at ieee.org
Mon Apr 10 15:25:52 EDT 2006


Tim Hochberg wrote:
> Kent Johnson wrote:
> 
>>David Bear wrote:
>>
>>
>>>I'm attempting to use the cgi module with code like this:
>>>
>>>import cgi
>>>fo = cgi.FieldStorage()
>>># form field names are in the form if 'name:part'
>>>keys = fo.keys()
>>>for i in keys:
>>>       try:
>>>               item,value=i.split(':')
>>>       except NameError, UnboundLocalError:
>>>               print "exception..."
>>>               item,value=(None,None)
>>>return(item,value)
>>>
>>>However, the except block does not seem to catch the exception and an
>>>unboundlocalerror is thrown anyway. What am I missing?
>>>       
>>
>>I don't know why you would get an UnboundLocalError from the above code, 
>>but the correct syntax is
>>   except (NameError, UnboundLocalError):
> 
> 
> One possibility is that there are no keys. Then the loop finishes 
> without ever setting item or values. This would give an unbound local 
> error. I assume that the OP would have noticed that in the traceback, 
> but perhaps he missed it.
> 
> OT, using i for the field namelike that makes my head hurt. Perhaps "for 
> fieldname in fo.keys():" would be in order instead.

This is bugging me. What's the above supposed to do? Right now, it 
iterates over all of the keys and returns item,value for the last key. 
That doesn't seem like that's what you want. Is it supposed to return a 
sequence of item, value pairs? If that's the case, I think you could 
just use:

     return [fieldname.split(':') for fieldname in fo]

Or, if you just want the last one, you could just tack a [-1] on the end 
of that, although it'll still bomb if there's no keys, so you might want 
to check.

The above assumes that FieldStorage faithfully implements the iter part 
of the dictionary protocol, something I'm not entirely sure about.

Regards,

-tim

> 
> 
>>Your code is binding the actual exception to the name "UnboundLocalError"
>>
>>Kent
> 
> 




More information about the Python-list mailing list