[Tutor] Python equiv of Perl's 'or die()' syntax

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 20 Jul 2000 01:00:03 +0200


On Wed, Jul 19, 2000 at 05:47:47PM -0500, Ben Beuchler wrote:
> Hmmm... OK.  I understand how that works.  Now, since I would like to
> include that kind of syntax on almost every file I open, any thoughts on
> doing something like this:
> 
> def safeopen(filename):
> 	try:
> 		handle = open(filename)
> 		return handle
> 	except IOError:
> 		print "Opening", filename, "failed!!"
> 
> And calling it thusly:
> 
> safeopen('worthlessfile')
> 
> Would that make sense as a shortcut?

Depends on what you want to do if it fails, I suppose. If you do f =
safeopen('bla'), you still have to handle the case where f is None, so
the function didn't help, really.

You should use the the try: except: construct at the place where you want to
handle the error condition.

If it's ok to quit the program when an error occurs (that's what "or die"
does, right?) just ignore the error, the program will halt with an error
message.

Well, that's my two cents, have to go sleep now :)
-- 
Remco Gerlich,  scarblac@pino.selwerd.nl