2 ms·
Your example proves his point. Suppose that permissions for the directory that the file is in got screwed up. (Or you're working in a new environment and they
by btilly 11y ago
Your example proves his point.
Suppose that permissions for the directory that the file is in got screwed up. (Or you're working in a new environment and they weren't set up right.) Your version gives no indication that anything went wrong. The version you dislike gives a helpful error message that says exactly what went wrong.
That error message can save a LOT of debugging time. Please make sure it is there.
- jdreaver 11y agoHowever, the first version has a race condition. The file might not exist between the if-statement check and the call to os.remove.
- btilly 11y agoThat sort of issue is why the best practice is to use careful routines like https://docs.python.org/2/library/tempfile.html https://docs.python.org/2/library/tempfile.html for temp files. But in practice on a trusted server, this kind of race condition doesn't actually happen. And if you have someone untrusted on your server, you already have a bigger problem than what you're fixing by getting the race condition right. By contrast the kind of permission problem that I mentioned is common, and I've spent too many hours debugging such issues in code other people wrote. (Ever tried to run old code on a new server that someone else tried to set up? You'd be amazed how many hidden dependencies will turn up...) That is why I consider the race condition to be less important than the exception swallowing anti-pattern.