What is the EAFP vs LBYL style, and which does Python prefer?
IntermediateConceptExceptions, context managers, files & logging
Answer
- LBYL (Look Before You Leap):
if path.exists(): path.read_text(). - EAFP (Easier to Ask Forgiveness than Permission):
try: path.read_text() except FileNotFoundError: ....
Python leans EAFP, and in ops code it is also more correct: between the check and the use, another process can delete the file or a resource can change state (a TOCTOU race). The same applies to AWS: try to create the bucket and handle BucketAlreadyOwnedByYou rather than checking first.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateHow does a `with` statement work, and why use it for files?BeginnerHow do you write your own context manager?Advanced