Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

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.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging