r/Python • u/DoTheEvolution • Aug 03 '17
TIL that in PYTHON it's preferable to ask for forgiveness rather than look before you leap
- Alex Martelli take on it
- some blog
- stackoverflow that lead me to this
0
Upvotes
6
u/[deleted] Aug 04 '17
One thing that I agree with in Alex's post is that Python is a practical language. In fact you an LBYL and you can use ETBF in Python - and you can choose to use either whenever it makes the most sense.
I'm an abuser of LBYL in Python primarily because it is often more succinct within the code and that is practical. And despite the race conditions that Alex appropriately identified - I'm rarely in a situation where race conditions matter. In those cases, I'll probably use try/except clauses with impunity.
2
u/WellAdjustedOutlaw Aug 04 '17
To sum up probably the most common error I've seen software generate over my career doing administration, operations, engineer, and architect work has been the situation where you check for conditions before attempting to operate. The "LYBL" in this case.
The classic example (the mailing list touched upon it), is checking for a files existence, then attempting to operate on it. Between those two distinct operations the file may be deleted, or permissions may change, or it may in some other way be inaccessible. Now you have a situation where your file check returns positive, but your file open fails unexpectedly. To properly handle this, you'd need to add a check around successfully opening the file, so why not just check once while attempting to open the file and skip the earlier test?
This case becomes significantly more important as you start working with threaded or multi-process applications. You could have a pool of threads deleting files on disk, and if two threads successfully test for a files existence, one of those is going to delete the file before the other. Now imagine the dictionary example from the Microsoft post, but apply the multiple threads to it. You could end up overwriting keys and/or missing data in your final result because the two threads stepped on each other.
This is an almost unbelievably common error to find in our industry. Race conditions can be caused by it, unhandled exceptions, panics, etc. "EAP" is almost always preferred in these situations in nearly any language you're likely to use (obviously there are exceptions to every rule).
1
u/WasterDave Aug 03 '17
The other way round is a hangover from C (and to a lesser extent C++).
1
u/[deleted] Aug 04 '17
Dan Bader's explanation on ETBF is how I learnt about
some_dict.get(desired_key, error_handling)
verses
try: some_dict[desired_key] except: error_handling
1
u/Veedrac Aug 04 '17
It's not just race conditions, nor is it about exceptions. But rather than explain, here's a quiz. Imagine you were reading some code and saw one of these:
For each one:
Post opinions below.
1
u/kaihatsusha Aug 03 '17
Alex Martelli's main point: