3 ms·
Exceptions when opening a file has been chosen because they have the nice propery of encouraging a race condition free EAFP rather than a hard to get right LBYL
by BiteCode_dev 7y ago
Exceptions when opening a file has been chosen because they have the nice propery of encouraging a race condition free EAFP rather than a hard to get right LBYL.
It also fits nicely into the context manager pattern.
Besides, remember exceptions are cheap in python. So cheap that for loops are basically syntaxic sugar for a try/catch.
- uep 7y agoFor those that don't know (I didn't): EAFP - Easier to ask for forgiveness than permission LBYL - Look before you leap They are opposite strategies, Python's preferred strategy is to do the first, just try the operation and throw an exception if it doesn't work. The second is to check a pre-condition before attempting an operation. I've always known the second as exhibiting TOCTOU, otherwise known as a time-of-check vs time-of-use race condition.
- LessDmesg 7y agoLBYL can easily be enforced by Maybe types, leaving exceptions for really exceptional things (which a nonexisting file definitely isn't). So we see how not having a real type system hurts and deforms a language in ways unrelated to types.
- Nullabillity 7y agoThat's still EAFP (you didn't check the precondition before trying), just through a different mechanism.
- acqq 7y agoBut that is a false claim. It's not about being EAFP or LBYL: if the open API returns a handle to file or null, the open operation can still be atomic and therefore race-free. Which is exactly how it's in all the programing languages and operating system calls which don't use exceptions for that. It's just the question if one has to write try-catch for something as common as file not existing.