473,325 Members | 2,785 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,325 software developers and data experts.

which one of these is better?

def create_sql_script(self):
try:
with open('labtables.sql') as sql_script:
return sql_script.read()
except IOError:
wx.MessageBox('Could not locate the file "labtables.sql"',
'File Not Found')
OR
def create_sql_script(self):
try:
f = open('labtables.sql')
sql_script = f.read()
except IOError:
wx.MessageBox('Could not locate the file "labtables.sql"',
'File Not Found')
finally:
f.close()

Do they both do the same thing?
Oct 26 '06 #1
7 1097
John Salerno wrote:
def create_sql_script(self):
try:
f = open('labtables.sql')
sql_script = f.read()
except IOError:
wx.MessageBox('Could not locate the file "labtables.sql"',
'File Not Found')
finally:
f.close()
Hmm, looks like this doesn't work anyway if open() doesn't work, because
then f.close() raises an UnboundLocalError for obvious reasons.
Oct 26 '06 #2
John Salerno enlightened us with:
Hmm, looks like this doesn't work anyway if open() doesn't work,
because then f.close() raises an UnboundLocalError for obvious
reasons.
Neither work 100% correct, actually. If the file can be located and
opened, but not read, the message

Could not locate the file "labtables.sql" File Not Found

is plain wrong.

Sybren
--
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
Oct 26 '06 #3
John Salerno wrote:
def create_sql_script(self):
try:
with open('labtables.sql') as sql_script:
return sql_script.read()
except IOError:
wx.MessageBox('Could not locate the file "labtables.sql"',
'File Not Found')
I can't comment on this, because it won't work in my implemention of
Python, I don't think.
>
OR
def create_sql_script(self):
try:
f = open('labtables.sql')
sql_script = f.read()
except IOError:
wx.MessageBox('Could not locate the file "labtables.sql"',
'File Not Found')
finally:
f.close()
Not really über-qualified to say anything, but I think that the
following would be better:

try:
f = open('file.sql')
script = f.read()
f.close()
except IOError:
wx.MessageBox('Message', 'Message Title')
>
Do they both do the same thing?
Not sure about the with-- I just went to read the PEP on it, and it
confused me greatly. :-) So, I don't know.

-- Mike
Oct 26 '06 #4
Michael B. Trausch wrote:
Not really über-qualified to say anything, but I think that the
following would be better:

try:
f = open('file.sql')
script = f.read()
f.close()
except IOError:
wx.MessageBox('Message', 'Message Title')
I was thinking of something like this actually.
Not sure about the with-- I just went to read the PEP on it, and it
confused me greatly. :-) So, I don't know.
Ditto. :)
Oct 26 '06 #5
John Salerno wrote:
>Not sure about the with-- I just went to read the PEP on it, and it
confused me greatly. :-) So, I don't know.

Ditto. :)
No need to be confused; the "with" statement is actually very simple.
Consider this piece of code:

set things up
try:
do something
finally:
tear things down

If you do this a lot, it would quite convenient if you could put the
"set things up" and "tear things down" code in a library function, so
you could reuse it. You can of course do something like

def controlled_execution(callback):
set things up
try:
callback(thing)
finally:
tear things down

def my_function(thing):
do something

controlled_execution(my_function)

but that's a bit verbose, especially if you need to modify local
variables. Another approach is to use a one-shot generator, and
abuse the for-in statement:

def controlled_execution():
set things up
try:
yield thing
finally:
tear things down

for thing in controlled_execution():
do something with thing

but this looks a bit weird, and doesn't even work in 2.4 and earlier.
So after contemplating a number of alternatives, GvR finally came up
with a generalization of the latter, using an object instead of a
generator to control the behaviour of an external piece of code:

class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down

with controlled_execution() as variable:
some code

When the "with" statement is executed, Python evaluates the expression,
calls the __enter__ method on the resulting value (which is called a
"context guard"), and assigns whatever __enter__ returns to the given
variable. Python will then execute the code body, and *no matter what
happens in that code*, call the guard object's __exit__ method.

For extra bonus, the __exit__ method can look at the exception, if any,
and suppress or modify it, if necessary. For example, the following
__exit__ method swallows any TypeError, but lets all other exceptions
through:

def __exit__(self, type, value, traceback):
return isinstance(value, TypeError)

In Python 2.5, the file object has been equipped with __enter__ and
__exit__ methods; the former simply returns the file object itself, and
the latter closes the file:
>>f = open("x.txt")
f
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>f.__enter__()
<open file 'x.txt', mode 'r' at 0x00AE82F0>
>>f.read(1)
'X'
>>f.__exit__(None, None, None)
f.read(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file

This wasn't very difficult, was it?

</F>

Oct 26 '06 #6
Fredrik Lundh wrote:
This wasn't very difficult, was it?
Well when you put it that way, no! :)

But one thing that caught me up was what happens if the initial
expression raises an exception? For example:

with open('file.txt'):
#do stuff

If the file can't be opened for whatever reason, does __exit__ get
called, or can it not get that far if the expression doesn't evaluate?

I guess my thinking was this: before the with statement came along, the
idiom for opening files was something like this:

try:
open('file.txt')
#do stuff
except IOError:
#more stuff
except OtherError:
#yet more

and so forth (and all this was wrapped in a try/finally blocked to close
the file, I think). But now that we can use the 'with' statement, it
seems like the initial opening of the file (previously "checked" in the
try block) is now just floating around and still requires a try block
wrapped around it in case something goes wrong.
Oct 26 '06 #7
Michael B. Trausch wrote:
Not really über-qualified to say anything, but I think that the
following would be better:

try:
f = open('file.sql')
script = f.read()
f.close()
except IOError:
wx.MessageBox('Message', 'Message Title')
>Do they both do the same thing?

Not sure about the with-- I just went to read the PEP on it, and it
confused me greatly. :-) So, I don't know.
when .read() fails the file will not be close here.

to replace the 'with' solution you#d need:
try:
f=open(path)
try:
script=f.read()
finally:
f.close()
except EnvironmentError,v:
wx.MessageBox(v, 'Message Title')


-robert
Oct 26 '06 #8

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

Similar topics

17
by: John Bentley | last post by:
John Bentley: INTRO The phrase "decimal number" within a programming context is ambiguous. It could refer to the decimal datatype or the related but separate concept of a generic decimal number....
8
by: Randell D. | last post by:
Folks, I once read an article in Linux Format whereby a technical writer had made performance recommendations on a LAMP environment. One of the points raised was for small columns in a database,...
65
by: Skybuck Flying | last post by:
Hi, I needed a method to determine if a point was on a line segment in 2D. So I googled for some help and so far I have evaluated two methods. The first method was only a formula, the second...
53
by: Jon S via DotNetMonster.com | last post by:
Hi all, I'm planning on developing an ASP.NET web site. I know both VB.NET and C# but am unsure on which would be more useful to develop an ASP.NET site with? Also I maybe looking to become a...
122
by: seberino | last post by:
I'm interested in knowing which Python web framework is most like Ruby on Rails. I've heard of Subway and Django. Are there other Rails clones in Python land I don't know about? Which one...
33
by: Protoman | last post by:
Which is better for general-purpose programming, C or C++? My friend says C++, but I'm not sure. Please enlighten me. Thanks!!!!!
114
by: Master Programmer | last post by:
Which do you prefer? Classic VB example: ************************* Private Sub Command1_Click() MsgBox "Hello, World" End Sub A VB.NET example: **************************
3
by: =?Utf-8?B?Um9sYW5kcGlzaA==?= | last post by:
Hi, I'm doing an application using C# and I have this question: I have a method called sqlQueryBD which receives a string sql query and executes it against a database. I also have a class called...
20
by: mike3 | last post by:
Hi. (Xposted to both comp.lang.c++ and comp.programming since I've got questions related to both C++ language and general programming) I've got the following C++ code. The first routine runs in...
5
by: Nitesh | last post by:
Objects of type X are basic building blocks of my application and there are a few functions which return XHandle (typedef X** XHandle). The task at hand needs to use a couple of these functions and...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.