Python Exceptions: EAFP and What is Really Exceptional?

前端 未结 5 2084
情话喂你
情话喂你 2020-12-02 21:37

It\'s been said in a couple places (here and here) that Python\'s emphasis on \"it\'s easier to ask for forgiveness than permission\" (EAFP) should be tempered with the idea

5条回答
  •  眼角桃花
    2020-12-02 22:02

    exceptions should only be called in truly exceptional cases

    Not in Python: for example, every for loop (unless it prematurely breaks or returns) terminates by an exception (StopIteration) being thrown and caught. So, an exception that happens once per loop is hardly strange to Python -- it's there more often than not!

    The principle in question may be crucial in other languages, but that's definitely no reason to apply that principle to Python, where it's so contrary to the language's ethos.

    In this case I like Jon's rewrite (which should be further simplified by removing the else branch) because it makes the code more compact -- a pragmatical reason, most definitely not the "tempering" of Python style with an alien principle.

提交回复
热议问题