Bare Excepts

Aahz aahz at pythoncraft.com
Sat Jan 2 12:40:44 EST 2010


In article <034f1009$0$1277$c3e8da3 at news.astraweb.com>,
Steven D'Aprano  <steve at REMOVE-THIS-cybersource.com.au> wrote:
>
>The try version is also better whenever there could be a race condition. 
>For example, when opening a file, you might be tempted to do this:
>
>if os.path.exists(filename):
>    f = open(filename, 'r')
>    text = f.read()
>else:
>    print "file missing"
>
>but that is dangerous in a multi-processing computer system (which nearly 
>all computers are these days). The problem is that in the fraction of a 
>second after you test that the file exists, some other process might come 
>along and delete it and the open call will then fail. So to be safe, you 
>have to do this:
>
>if os.path.exists(filename):
>    try:
>        f = open(filename, 'r')
>    except IOError:
>        print "file missing"
>    else:
>        text = f.read()
>else:
>    print "file missing"
>
>But of course now the test is redundant, and all you really need is the 
>try...except block:
>
>try:
>    f = open(filename, 'r')
>except IOError:
>    print "file missing"
>else:
>    text = f.read()

OTOH, if you want to do something different depending on whether the file
exists, you need to use both approaches:

if os.path.exists(fname):
    try:
        f = open(fname, 'rb')
        data = f.read()
        f.close()
        return data
    except IOError:
        logger.error("Can't read: %s", fname)
        return ''
else:
    try:
        f = open(fname, 'wb')
        f.write(data)
        f.close()
    except IOError:
        logger.error("Can't write: %s", fname)
    return None

(This is a somewhat stupid example strictly for illustration.  A better
and more-elaborate example would be something like trying to copy a file
to fname and rename an existing file to '.bak' if it exists.  The tricky
part would be trying to rename the '.bak' to fname if the copy fails.
And yes, that's exactly what some code I wrote a few days ago does.)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.



More information about the Python-list mailing list