try...except...finally problem in Python 2.5
Jean-Paul Calderone
exarkun at divmod.com
Wed Feb 14 14:48:57 EST 2007
On 14 Feb 2007 11:41:29 -0800, redawgts <redawgts at gmail.com> wrote:
>I keep getting this error "local variable 'f' referenced before
>assignment" in the finally block when I run the following code.
>
> try:
> f = file(self.filename, 'rb')
> f.seek(DATA_OFFSET)
> self.__data = f.read(DATA_SIZE)
> self.isDataLoaded = True
> except:
> self.isDataLoaded = False
> finally:
> f.close()
>
>Can someone tell me what's wrong with the code? Am I doing something
>wrong? I'm somewhat new to python but this makes sense to me.
>
f is not bound until the first line of the try suite has completely
successfully executed. If it fails to do this, for example because
self.filename is an attribute error, or the filename given by that
attribute does not exist, then the finally suite will execute before
f has been bound, and the UnboundLocalError will mask the real error.
Jean-Paul
More information about the Python-list
mailing list