473,406 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

try...except...finally problem in Python 2.5

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.

Feb 14 '07 #1
11 3196
"redawgts" <re******@gmail.comwrote in message
news:11*********************@l53g2000cwa.googlegro ups.com...
>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.
If the call to file raises an exception, then variable f won't have been
created.

Here's a simple example:

def f():
throw 42
try:
x = f()
except:
print x

Try it and see what happens. While you're at it, you might try to figure
out what you would like it to print.

Feb 14 '07 #2
redawgts 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.
Move the "f = file(self.filename, 'rb')" above the try:. If opening the file
happens to throw an exception, then the assignment will never happen and there
will be no 'f' to close.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Feb 14 '07 #3
redawgts 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.
finally: block is executed even if there is an exception in which case f
hasn't been defined. What you want is:

try:
f = file(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

except:
isDataLoaded=False

else:
f.close()

-Larry
Feb 14 '07 #4
"redawgts" <re******@gmail.comwrites:
try:
f = file(self.filename, 'rb') ...
Can someone tell me what's wrong with the code?
Various people have explained the error: if the file open attempt
fails, f is never assigned. Doing it the right way (i.e. handling the
potential exceptions separately) with try/except statements is messy,
so it's worth mentioning that 2.5 adds the new "with" statement to
clean this up. I'm not using 2.5 myself yet so maybe someone will
have to correct me, but I think you'd write:

from __future__ import with_statement

self.isDataLoaded = False
with open(self.filename, 'rb') as f:
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

and that should handle everything, closing the file automatically.
Feb 14 '07 #5
Thanks everybody, that helped alot.

Feb 14 '07 #6
On Wed, 14 Feb 2007 12:09:34 -0800, Paul Rubin wrote:
"redawgts" <re******@gmail.comwrites:
> try:
f = file(self.filename, 'rb') ...
Can someone tell me what's wrong with the code?

Various people have explained the error: if the file open attempt
fails, f is never assigned. Doing it the right way (i.e. handling the
potential exceptions separately) with try/except statements is messy,
so it's worth mentioning that 2.5 adds the new "with" statement to
clean this up. I'm not using 2.5 myself yet so maybe someone will
have to correct me, but I think you'd write:

from __future__ import with_statement

self.isDataLoaded = False
with open(self.filename, 'rb') as f:
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True

and that should handle everything, closing the file automatically.

I don't have Python 2.5 here to experiment, but how is that different from
this?
self.isDataLoaded = False
try:
f = open(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
pass
else:
pass

(apart from being four lines shorter)

--
Steven D'Aprano

Feb 15 '07 #7
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
self.isDataLoaded = False
try:
f = open(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
pass
else:
pass

(apart from being four lines shorter)
Your version never closes the file.
Feb 15 '07 #8
On Wed, 14 Feb 2007 18:03:19 -0800, Paul Rubin wrote:
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
>self.isDataLoaded = False
try:
f = open(self.filename, 'rb')
f.seek(DATA_OFFSET)
self.__data = f.read(DATA_SIZE)
self.isDataLoaded = True
except:
pass
else:
pass

(apart from being four lines shorter)

Your version never closes the file.

Yes it does. Eventually f goes out of scope and is closed automatically.

I don't see where the "with" version closes the file either. How does it
know that I want to call the f's close() method, rather than, say,
f.exit() or f.do_something_else()?

--
Steven D'Aprano

Feb 15 '07 #9
Replying to my own question...

On Thu, 15 Feb 2007 13:17:00 +1100, Steven D'Aprano wrote:
I don't see where the "with" version closes the file either. How does it
know that I want to call the f's close() method, rather than, say,
f.exit() or f.do_something_else()?
Ah, I *think* I see... file objects in Python 2.5 are objects that know
how to work with the "with" statement; that is they obey the "context
management" protocol and have __enter__ and __exit__ methods that do the
right thing to make everything work correctly.

http://docs.python.org/whatsnew/pep-343.html

Have I got it right?
--
Steven D'Aprano

Feb 15 '07 #10
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
Yes it does. Eventually f goes out of scope and is closed automatically.
Oh right, however you can't really predict when the closure occurs,
unless you're relying on current CPython artifacts.

Re your other post: yes, PEP 363 explains how the "with" statement
calls the __exit__ method.
Feb 15 '07 #11
Paul Rubin <http://ph****@NOSPAM.invalidwrites:
Re your other post: yes, PEP 363 explains how the "with" statement
Whoops, 343.
Feb 15 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Raymond Arthur St. Marie II of III | last post by:
Del's "except"ional PEP Rejection Ladieees and Gentilmen and Pyth-O-neers of all ages. Step right up. Don't be shy. Come one come all. Be the first on your block TO GROK *THE* one *THE* only...
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
12
by: Brian Kelley | last post by:
def res(): try: a = 1 return finally: print "do I get here?" res() outputs "do I get here?"
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
9
by: David Stockwell | last post by:
In referring to my copy of the python bible, it tells me I can't use all three items 'try' except and finally. I can use the t/f or t/e combinations though What combination can i use if i want...
1
by: djw | last post by:
c.l.p- I am having trouble understanding how one is supposed to correctly utilize try:...except:...finally: in real code. If I have a block of code like: def foo(): try: ... some code that...
5
by: Robert Hicks | last post by:
Is it good practice to do something like: try: f1 = file('file1') f2 = file('file2') except: # catch the exception Or do you do a try/except for each open?
5
by: Ed Jensen | last post by:
I'm using: Python 2.3.2 (#1, Oct 17 2003, 19:06:15) on sunos5 And I'm trying to execute: #! /usr/bin/env python try:
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.