For 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.
But 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.
Re:Exceptions should be Exceptional (2016)
by LessDmesg on Friday March 13, 2020 @10:27AM
(#22567482)
LBYL 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.
Re:Exceptions should be Exceptional (2016)
by Nullabillity on Friday March 13, 2020 @12:26PM
(#22568596)
That's still EAFP (you didn't check the precondition before trying), just through a different mechanism.
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.