在Python中使用assert的例子? [英] Example use of assert in Python?
问题描述
我已经阅读了关于何时使用断言与异常,但我还没有得到它。似乎每当我认为我处于使用断言的情况下,后来在开发中,我发现我是在我飞跃之前,以确保在调用该函数时该断言不会失败。由于还有一个Python习惯用于尝试使用try-except,所以我通常最终会断言assert并抛出一个异常。我还没有找到一个似乎使用断言的地方。任何人都可以提出一些很好的例子?
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?
推荐答案
一个很好的指导是使用 assert
它的触发意味着代码中的错误。当你的代码假设某事并采取行动时,建议用断言
来保护这个假设。 断言
失败意味着您的假设不正确,这意味着您的代码不正确。
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.
这篇关于在Python中使用assert的例子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!