Comparison with False - something I don't understand

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Dec 4 20:59:27 EST 2010


On Sat, 04 Dec 2010 17:07:45 +0000, Harishankar wrote:

> I find a bit cumbersome
> that exceptions are advocated for certain conditions which can be sanely
> worked around in the application's logic and even avoided, rather than
> waiting for them to get caught and providing an unsatisfactory result.

That's surprisingly rare in Python. In fact, I'd go so far as to say that 
in Python there is *nothing* that you can test for and then have a 
*guarantee* that it will succeed.

Of course, this is mainly of theoretical concern. In practice, "Look 
Before You Leap" (test first, then process) is often fine. But there are 
traps to look out for. For example, unless you are running a single-
process machine, the following code is subject to race conditions and is 
not safe:

if os.exists(pathname):
    fp = open(pathname)
else:
    handle_missing_file()

Just because the file is there when os.exists() looks for it, doesn't 
mean it still exists a microsecond later when you try opening it.

Or consider this code:

if y != 0:
    result = x/y
else:
    handle_division_by_zero()


This is also unsafe unless you know the type of y. Suppose y is an 
interval quantity that straddles zero, then division by y may fail even 
though y != 0.


-- 
Steven



More information about the Python-list mailing list