unboundlocalerror with cgi module
Kent Johnson
kent at kentsjohnson.com
Mon Apr 10 15:20:13 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.
I think that would be a NameError for the code shown because item and
value are global variables. 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.
Kent
More information about the Python-list
mailing list