Cheap exception handling in Python?

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

    I am a python beginner as well. While I cannot say why exactly Exception handling has been called cheap in the context of that answer, here are my thoughts:

    Note that checking with if-elif-else has to evaluate a condition every time. Exception handling, including the search for an exception handler occurs only in an exceptional condition, which is likely to be rare in most cases. That is a clear efficiency gain. As pointed out by Jay, it is better to use conditional logic rather than exceptions when there is a high likelihood of the key being absent. This is because if the key is absent most of the time, it is not an exceptional condition.

    That said, I suggest that you don't worry about efficiency and rather about meaning. Use exception handling to detect exceptional cases and checking conditions when you want to decide upon something. I was reminded about the importance of meaning by S.Lott just yesterday.

    Case in point:

    def xyz(key):
       dictOb = {x:1, y:2, z:3}
       #Condition evaluated every time
       if dictOb.has_key(key):  #Access 1 to dict
            print dictOb[key]  #Access 2
    

    Versus

    #Exception mechanism is in play only when the key isn't found.
    def xyz(key):
       dictOb = {x:1, y:2, z:3}
       try:
            print dictOb[key]  #Access 1
       except KeyError:
            print "Not Found"
    

    Overall, having some code that handles something,like a missing key, just in case needs exception handling, but in situations like when the key isn't present most of the time, what you really want to do is to decide if the key is present => if-else. Python emphasizes and encourages saying what you mean.

    Why Exceptions are preferred to if-elif ->

    1. It expresses the meaning more clearly when you are looking foe exceptional aka unusual/unexpected conditions in your code.
    2. It is cleaner and a whole lot more readable.
    3. It is more flexible.
    4. It can be used to write more concise code.
    5. Avoids a lot of nasty checking.
    6. It is more maintainable.

    Note When we avoid using try-except, Exceptions continue being raised. Exceptions which aren't handled simply go to the default handler. When you use try-except, you can handle the error yourself. It might be more efficient because if-else requires condition evaluation, while looking for an exception handler may be cheaper. Even if this is true, the gain from it will be too minor to bother thinking about.

    I hope my answer helps.

    0 讨论(0)
  • 2020-12-05 18:32

    Don't sweat the small stuff. You've already picked one of the slower scripting languages out there, so trying to optimize down to the opcode is not going to help you much. The reason to choose an interpreted, dynamic language like Python is to optimize your time, not the CPU's.

    If you use common language idioms, then you'll see all the benefits of fast prototyping and clean design and your code will naturally run faster as new versions of Python are released and the computer hardware is upgraded.

    If you have performance problems, then profile your code and optimize your slow algorithms. But in the mean time, use exceptions for exceptional situations since it will make any refactoring you ultimately do along these lines a lot easier.

    0 讨论(0)
提交回复
热议问题