unboundlocalerror with cgi module

bruno at modulix onurb at xiludom.gro
Tue Apr 11 10:18:06 EDT 2006


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

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').


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list