Example use of assert in Python?

后端 未结 4 2177
庸人自扰
庸人自扰 2021-02-04 12:06

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

4条回答
  •  长发绾君心
    2021-02-04 12:58

    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
    

提交回复
热议问题