Cheap exception handling in Python?

后端 未结 8 1068
广开言路
广开言路 2020-12-05 17:34

I read in an earlier answer that exception handling is cheap in Python so we shouldn\'t do pre-conditional checking.

I have not heard of this before, but I\'m relati

8条回答
  •  被撕碎了的回忆
    2020-12-05 18:25

    "Can someone explain this to me?"

    Depends.

    Here's one explanation, but it's not helpful. Your question stems from your assumptions. Since the real world conflicts with your assumptions, it must mean your assumptions are wrong. Not much of an explanation, but that's why you're asking.

    "Exception handling means a dynamic call and a static return, whereas an if statement is static call, static return."

    What does "dynamic call" mean? Searching stack frames for a handler? I'm assuming that's what you're talking about. And a "static call" is somehow locating the block after the if statement.

    Perhaps this "dynamic call" is not the most costly part of the operation. Perhaps the if-statement expression evaluation is slightly more expensive than the simpler "try-it-and-fail".

    Turns out that Python's internal integrity checks are almost the same as your if-statement, and have to be done anyway. Since Python's always going to check, your if-statement is (mostly) redundant.

    You can read about low-level exception handling in http://docs.python.org/c-api/intro.html#exceptions.


    Edit

    More to the point: The if vs. except debate doesn't matter.

    Since exceptions are cheap, do not label them as a performance problem.

    Use what makes your code clear and meaningful. Don't waste time on micro-optimizations like this.

提交回复
热议问题