Example use of assert in Python?

让人想犯罪 __ 提交于 2019-12-04 08:32:54

问题


I've read about when to use assert vs. exceptions, but I'm still not "getting it". It seems like whenever I think I'm in a situation where I should use assert, later on in development I find that I'm "looking before I leap" to make sure the assert doesn't fail when I call the function. Since there's another Python idiom about preferring to use try-except, I generally end up ditching the assert and throwing an exception instead. I have yet to find a place where it seems right to use an assert. Can anyone come up with some good examples?


回答1:


A good guideline is using assert when its triggering means a bug in your code. When your code assumes something and acts upon the assumption, it's recommended to protect this assumption with an assert. This assert failing means your assumption isn't correct, which means your code isn't correct.




回答2:


tend to use assert to check for things that should never happen. sort of like a sanity check.

Another thing to realize is that asserts are removed when optimized:

The current code generator emits no code for an assert statement when optimization is requested at compile time.




回答3:


Generelly, assert is there to verify an assumption you have about your code, i.e. at that point in time, either the assert succeeds, or your implementation is somehow buggy. An exception is acutally expecting an error to happen and "embracing" it, i.e. allowing you to handle it.




回答4:


A good example is checking the arguments of a function for consistency:

def f(probability_vector, positive_number):
    assert sum(probability_vector) == 1., "probability vectors have to sum to 1"
    assert positive_number >= 0., "positive_number should be positive"
    # body of function goes here


来源:https://stackoverflow.com/questions/3721126/example-use-of-assert-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!