unboundlocalerror with cgi module

Tim Hochberg tim.hochberg at ieee.org
Mon Apr 10 15:45:49 EDT 2006


Kent Johnson wrote:
> 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.
> 
> 
> I think that would be a NameError for the code shown because item and 
> value are global variables.

Note that there is a return at the end of the posted code, so I suspect 
that this problem actually occurs in a function somewhere and the OP 
"simplified" things in order to post it.

  But anyway you raise a good point that
> perhaps the reason the exception is not being caught is because it is 
> raised by code outside the scope of the try.

> 
> Also UnboundLocalError is a subclass of NameError so catching NameError 
> should catch UnboundLocalError as well.

Good point.

-tim




More information about the Python-list mailing list