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

Sean 'Shaleh' Perry shaleh@valinux.com
Wed, 19 Jul 2000 15:52:53 -0700 (PDT)

> 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?

well, the caller would not get a return value, so unless you exit in
safeopen(), the next line of your script will have issues:

file = safeopen('myfile') # file does not exist
for line in file.readlines: # oops, file is not set to anything
        print line