Why assert is not largely used?

后端 未结 4 1170
情深已故
情深已故 2021-01-31 13:13

I found that Python\'s assert statement is a good way to catch situations that should never happen. And it can be removed by Python optimization when the code is trusted to be c

4条回答
  •  余生分开走
    2021-01-31 14:13

    I'm not an author of any of those projects, so this is just a guess based on my own experiences. Without directly asking people in those projects you won't get a concrete answer.

    Assert is great when you're trying to do debugging, etc in your own application. As stated in the link you provided, however, using a conditional is better when the application might be able to predict and recover from a state. I haven't used zope, but in both Twisted and Django, their applications are able to recover and continue from many errors in your code. In a sense, they have already 'compiled away' the assertions since they actually can handle them.

    Another reason, related to that, is that often applications using external libraries such as those you listed might want to do error handling. If the library simply uses assertions, no matter what the error is it will raise an AssertionError. With a conditional, the libraries can actually throw useful errors that can be caught and handled by your application.

提交回复
热议问题