473,320 Members | 1,865 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,320 software developers and data experts.

getting with statement to deal with various exceptions

mk
Hello,

I'm trying to learn how with statement can be used to avoid writing:

prepare()
try:
something_that_can_raise_SomeException()
except SomeException, err:
deal_with_SomeException
finally:
tear_it_down()

Verbose, not very readable. OK, "with" to the rescue?

Let's take a textbook example from PEP:

with open('/etc/passwd', 'r') as f:
BLOCK

Well, great, it's neat that "with" closes the file after BLOCK has
finished execution, but what if the file isn't there and attempt to open
it raises IOException? I'd like to be able to catch it precisely to
avoid writing verbose try: .. except: .. finally: .. blocks which as I
understand has been much of the rationale behind creating "with"
statement in the first place.

"with" statement only allows easy dealing with prepare() and
tear_it_down(). When I try to get it to deal with exceptions that might
happen, it becomes more complicated:

class FileContextManager:
def __enter__(self, filename, mode):
f = open(filename, mode)
return f
def __exit__(self, etype, evalue, etraceback):
print "etype", etype, "evalue", evalue, "etraceback", etraceback

>>with FileContextManager("somefile", "r") as f:
a = f.readlines()

Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
with FileContextManager("somefile", "r") as f:
TypeError: this constructor takes no arguments
Bummer.

Plus, no documentation I've read (on effbot, in PEP 343, etc) says how
to deal with the exception happening in __enter__ method of context
manager, which is precisely what I'd like to do.

This is only natural, isn't it? When e.g. reading the file, preparation
phase is typically checking if it can be opened in the first place. So
it falls into __enter__ method of context manager.

"with" limited only to successful execution of a_statement from "with
a_statement" seems like limited benefit to me.

I'd like to be able to write smth like

class FileContextManager:
def __enter__(self, filename, mode):
f = open(filename, mode)
return f
def __except__(IOError, err):
do_this
print err
def __except__(RuntimeError, err):
do_that
print "something bad happened", err
def __exit__(self, etype, evalue, etraceback):
print "etype", etype, "evalue", evalue, "etraceback", etraceback

__exit__ deals with exceptions happening in the BLOCK below "with"
statement, not with exceptions raised in "a_statement", when executing

with a_statement as var:
BLOCK

In the above way "with" would give me the benefit of more terse, but
still understandable and efficient code.

Well, I can always do this:

try:
with open("somefile.txt") as txtfile:
for line in txtfile:
print line
except IOError:
print "No such file."
No such file.
But that's just ugly, nested too many times (flat is better than nested,
right?) and not all that more readable.

Jul 20 '08 #1
2 1385

"mk" <mr****@gmail.comwrote in message
news:ma************************************@python .org...
Hello,

I'm trying to learn how with statement can be used to avoid writing:

prepare()
try:
something_that_can_raise_SomeException()
except SomeException, err:
deal_with_SomeException
finally:
tear_it_down()

Verbose, not very readable. OK, "with" to the rescue?

Let's take a textbook example from PEP:

with open('/etc/passwd', 'r') as f:
BLOCK

Well, great, it's neat that "with" closes the file after BLOCK has
finished execution, but what if the file isn't there and attempt to open
it raises IOException? I'd like to be able to catch it precisely to avoid
writing verbose try: .. except: .. finally: .. blocks which as I
understand has been much of the rationale behind creating "with" statement
in the first place.

"with" statement only allows easy dealing with prepare() and
tear_it_down(). When I try to get it to deal with exceptions that might
happen, it becomes more complicated:

class FileContextManager:
def __enter__(self, filename, mode):
f = open(filename, mode)
return f
def __exit__(self, etype, evalue, etraceback):
print "etype", etype, "evalue", evalue, "etraceback", etraceback

>with FileContextManager("somefile", "r") as f:
a = f.readlines()

Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
with FileContextManager("somefile", "r") as f:
TypeError: this constructor takes no arguments
Bummer.

Plus, no documentation I've read (on effbot, in PEP 343, etc) says how to
deal with the exception happening in __enter__ method of context manager,
which is precisely what I'd like to do.

This is only natural, isn't it? When e.g. reading the file, preparation
phase is typically checking if it can be opened in the first place. So it
falls into __enter__ method of context manager.

"with" limited only to successful execution of a_statement from "with
a_statement" seems like limited benefit to me.

I'd like to be able to write smth like

class FileContextManager:
def __enter__(self, filename, mode):
f = open(filename, mode)
return f
def __except__(IOError, err):
do_this
print err
def __except__(RuntimeError, err):
do_that
print "something bad happened", err
def __exit__(self, etype, evalue, etraceback):
print "etype", etype, "evalue", evalue, "etraceback", etraceback

__exit__ deals with exceptions happening in the BLOCK below "with"
statement, not with exceptions raised in "a_statement", when executing

with a_statement as var:
BLOCK

In the above way "with" would give me the benefit of more terse, but still
understandable and efficient code.

Well, I can always do this:

try:
with open("somefile.txt") as txtfile:
for line in txtfile:
print line
except IOError:
print "No such file."
No such file.
But that's just ugly, nested too many times (flat is better than nested,
right?) and not all that more readable.
I just started looking at the with statement myself. How about:

from __future__ import with_statement

class ExceptionManager(object):
def __enter__(self):
pass
def __exit__(self,exc_type,exc_value,tb):
if exc_type == IOError:
print 'IOError',exc_value[1]
return True # suppress it

with ExceptionManager():
with open('test.txt') as f:
f.read()

--
Mark

Jul 20 '08 #2
mk
from __future__ import with_statement

class ExceptionManager(object):
def __enter__(self):
pass
def __exit__(self,exc_type,exc_value,tb):
if exc_type == IOError:
print 'IOError',exc_value[1]
return True # suppress it

with ExceptionManager():
with open('test.txt') as f:
f.read()
Neat. I think I'm going to use this approach, since BDFL-in-chief is
unlikely to listen to me in any foreseeable future. :-)

Jul 20 '08 #3

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

Similar topics

5
by: Toby Donaldson | last post by:
Hi all, I'm designing an educational application that will run Python code and check the output against a pre-define answer. I want to use the "exec" statement to run the code, but I don't know...
5
by: Jacek Dziedzic | last post by:
Hi! In my main() function I have a last-resort exception construct that looks like this: int main() { try { // ... program code }
3
by: Kendall Gifford | last post by:
Greetings. While trying to get a simple app working, I've been forced to delve into embedded and/or linked resources a bit. I read all the reference for the System.Resources namespace as well as...
27
by: Richard Blewett [DevelopMentor] | last post by:
I've just seen on Eric Gunnerson's blog that C# is getting Edit and Continue in Whidbey. That will please alot of people - although me, I have mixed feelings about it ;-) ...
6
by: cody | last post by:
Mostly always you use the using clause you deal with native ressources, so exception handlinjg is sooner or later inevitable. so why do we need to write try { using (File f =...
5
by: Peter Steele | last post by:
We have an application that when it runs in the IDE in debug mode an unhandled exception is occurring in a system header file associated with STL stirngs. The actual statement that crashes is ...
20
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
9
by: Jameson.Quinn | last post by:
I have: try: for line in open(myFileName): count += 1 except IOError: print "Can't open myfile" (I know, this is bad, I never close the file, but its just for illustration). But then I...
1
by: mohit1286 | last post by:
my stored procedure in db2 is---> create procedure temp_bill(in UPC_cd character(6)) language sql begin declare prod_cd character(8);declare prod_desc varchar(30);declare discount...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
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
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
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)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.