exception handling in complex Python programs

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Aug 19 19:12:16 EDT 2008


On Tue, 19 Aug 2008 11:07:39 -0700, dbpokorny at gmail.com wrote:

>   def do_something(filename):
>     if not os.access(filename,os.R_OK):
>       return err(...)
>     f = open(filename)
>     ...


You're running on a multitasking modern machine, right? What happens when 
some other process deletes filename, or changes its permissions, in the 
time after you check for access but before you actually open it?

This isn't just a theoretical risk. There's a whole class of errors and 
security holes based on similar race conditions. I find it amusing that 
you consider it "sloppy" to deal with errors raised when actually opening 
a file, but then recommend a technique that has a well-known failure mode.

That's not to say that I never use such techniques myself. For quick and 
dirty scripts, where I can tolerate the risk of some other process moving 
a file behind my back, I've been known to do something similar.



-- 
Steven



More information about the Python-list mailing list