n00b confusion re: local variable referenced before assignment error

Mike Kazantsev mk.fraggod at gmail.com
Fri Jun 19 12:36:38 EDT 2009

On Fri, 19 Jun 2009 11:16:38 -0500
Wells Oliver <wells at submute.net> wrote:

>         def save(self, uri, location):
>                 try:
>                         handler = urllib2.urlopen(uri)
>                 except urllib2.HTTPError, e:
>                         if e.code == 404:
>                                 return
>                         else:
>                                 print "retrying %s (HTTPError)" % uri
>                                 time.sleep(1)
>                                 self.save(uri, location)
>                 except urllib2.URLError, e:
>                         print "retrying %s" % uri
>                         time.sleep(1)
>                         self.save(uri, location)
>                 if not os.path.exists(os.path.dirname(location)):
>                         os.makedirs(os.path.dirname(location))
>                 file = open(location, "w")
>                 file.write(handler.read())
>                 file.close()

> But what I am seeing is that after a retry (on catching a URLError
> exception), I see bunches of "UnboundLocalError: local variable 'handler'
> referenced before assignment" errors on line 38, which is the
> "file.write(handler.read())" line..
> What gives?

Why not?
Try fails, except calls retry and after the retry code execution
continues to the undefined "handler", since the try has failed here.
You might want to insert return or avoid (possibly endless) recursion
altogether - just wrap it into while loop with some counter (aka

Also, you can get rid of code duplication by catching some basic
urllib2 exception, then checking if it's urllib2.HTTPError and it's code
is 404, retrying ("continue" for the loop case) otherwise.

Mike Kazantsev // fraggod.net
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 205 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20090619/05bedf1c/attachment-0001.sig>

More information about the Python-list mailing list