Python's EAFP Approach: Why Exceptions are Preferred

Why Python prefers 𝘵𝘳𝘺 / 𝘦𝘹𝘤𝘦𝘱𝘵 over 𝘪𝘧 𝘦𝘭𝘴𝘦 checks? TL;DR: In Python, exceptions are part of normal flow, not rare events! There are two ways to walk through a uncertain code block - 1. Look Before You Leap (LBYL) - - Check conditions before doing the action - The 𝘪𝘧 𝘦𝘭𝘴𝘦 statements. - But here, Python looks at the dictionary twice. Once to check if the key exists, and once to actually fetch it. 2. Easier to Ask Forgiveness than Permission (EAFP) - Assume things will work and wrap the action in a try block. - If the key exists (which is usually the case), execution stays on the fast path. EAFP is the "Pythonic" approach. It is the way Python is built internally too. Python uses exceptions internally for everything. When using a for loop, Python doesn't check the length of the list; it just keeps asking for items until the list raises a StopIteration exception. Takeaway - -> Using try excepts will not add to any extra processing time, if not reduce it in most of the practical cases. -> Use LBYL if the failure is expected to happen often. -> Use EAFP if the failure is unexpected and rare. I’m deep-diving into Python internals and performance. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment

  • graphical user interface, text, application, email

To view or add a comment, sign in

Explore content categories