Cheap exception handling in Python?

后端 未结 8 1058
广开言路
广开言路 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:17

    What are static versus dynamic calls and returns, and why do you think that calls and returns are any different in Python depending on if you are doing it in a try/except block? Even if you aren't catching an exception, Python still has to handle the call possibly raising something, so it doesn't make a difference to Python in regards to how the calls and returns are handled.

    Every function call in Python involves pushing the arguments onto the stack, and invoking the callable. Every single function termination is followed by the caller, in the internal wiring of Python, checking for a successful or exception termination, and handles it accordingly. In other words, if you think that there is some additional handling when you are in a try/except block that is somehow skipped when you are not in one, you are mistaken. I assume that is what you "static" versus "dynamic" distinction was about.

    Further, it is a matter of style, and experienced Python developers come to read exception catching well, so that when they see the appropriate try/except around a call, it is more readable than a conditional check.

提交回复
热议问题