473,804 Members | 2,034 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

which one of these is better?

def create_sql_scri pt(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_scri pt(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 1115
John Salerno wrote:
def create_sql_scri pt(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 UnboundLocalErr or 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 UnboundLocalErr or 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_scri pt(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_scri pt(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_exec ution(callback) :
set things up
try:
callback(thing)
finally:
tear things down

def my_function(thi ng):
do something

controlled_exec ution(my_functi on)

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_exec ution():
set things up
try:
yield thing
finally:
tear things down

for thing in controlled_exec ution():
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_exec ution:
def __enter__(self) :
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down

with controlled_exec ution() 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(valu e, 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__(No ne, 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 EnvironmentErro r,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
6157
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. "Decimal Number" sometimes serves to distinguish Base 10 numbers, eg "15", from Base 2 numbers, Eg "1111". At other times "Decimal Number" serves to differentiate a number from an integer. For the rest of this post I shall only use either...
8
6280
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, that one is perhaps better off to trade a small waste of space for a gain on performance - The recommendation said that when you use VARCHAR(3) that MySQL searches for disk space to take a record that will accept a variable length value up to...
65
12634
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 method was a piece of C code which turned out to be incorrect and incomplete but by modifieing it would still be usuable. The first method was this piece of text:
53
3321
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 web developer in the future so it would help if I use the langauge that most companies use to develop their ASP.NET site? Many thanks, Jon.
122
7927
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 has largest community/buzz about it?
33
2592
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
3430
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
1284
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 sqlCompat which has one property "sqlText" with its getter and setter methods. The purpose of this class to translate the receiving sql query into an "escaped" sql query, for instance: insert into people values ('cod001','Carl...
20
3102
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 like 65% of the time of the second routine. Yet both do the same thing. However, the second one seems better in terms of the way the code is written since it helps encapsulate the transformation in the inner loop better making it easier to read,...
5
1403
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 then iterate over X objects. Because its done frequently and it separates iteration from task-at- hand'logic we decided to create iterator. Assuming the availability of functions GetXHandleSize(XHandle) and DisposeXHandle(XHandle) there are...
0
9711
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9591
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10594
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10087
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.