unboundlocalerror with cgi module

D

David Bear

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?
 
F

Felipe Almeida Lessa

Em Seg, 2006-04-10 às 11:29 -0700, David Bear escreveu:
However, the except block does not seem to catch the exception and an
unboundlocalerror is thrown anyway. What am I missing?

See http://docs.python.org/tut/node10.html :

"""
A try statement may have more than one except clause, to specify
handlers for different exceptions. At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try
clause, not in other handlers of the same try statement. An except
clause may name multiple exceptions as a parenthesized tuple, for
example:

.... except (RuntimeError, TypeError, NameError):
.... pass
"""
 
K

Kent Johnson

David said:
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):

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

Kent
 
T

Tim Hochberg

Kent said:
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.

Regards,

-tim
 
K

Kent Johnson

Tim said:
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
 
T

Tim Hochberg

Tim said:
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
 
F

Fredrik Lundh

David Bear said:
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?

why on earth do you expect a string split to result in either a NameError
or an UnboundLocalError ? (both of which signify *programming* errors,
most likely in *your* code, and should be fixed rather than ignored)

</F>
 
T

Tim Hochberg

Kent said:
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
 
B

bruno at modulix

David said:
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

Which one ?-)
and an
unboundlocalerror is thrown anyway. What am I missing?

Err...

1/ the correct try/except syntax is:
try:
whatever_that_may_raise()
except (ExceptionClass1, ExceptionClassN):
handle_the_exception()

What you code would actually do (if it raised a NameError, which will
not be the case, cf next point) is to *bind* the exception object to the
name 'UnboundLocalError'.

2/ the line:
item,value=i.split(':')
*won't* raise NameError nor UnboundLocalError


3/ if fo.keys() returns a non-empty list, your code (that I assume is
the body of a function) will return the result of the split() for the
*last* item in the list (after having uselessly split'ed each and every
key...)

4/ else (ie : fo.keys() returns an empty list), *then* you'll get an
UnboundLocalError (once again, assuming this code is the body of a
function - but else you'd get a SyntaxError, since the return statement
is not allowed outside a function body), *but* this exception will be
raised when the 'return' statement is executed - not in the loop.


A corrected version of your code could be:

def extract_last_key(field_storage):
# form field names are in the form if 'name:part'
keys = field_storage.keys()
if keys:
return keys[-1].split(':', 1)
else:
return (None, None)

import cgi
fo = cgi.FieldStorage()
name, part = extract_last_key(fo)

I doubt this is actually what you *really* want, but this is at least
what your code effectively try to do.

FWIW, trying things at random until it seems to work is the worst way to
program (some call this 'programming by accident').
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top