Python 中断言的使用示例?

发布于 2024-09-19 00:03:36 字数 183 浏览 8 评论 0原文

我已经读过有关何时使用断言与异常的信息,但我仍然没有“明白”。似乎每当我认为我处于应该使用断言的情况时,在后来的开发中我发现我正在“三思而后行”以确保当我调用函数时断言不会失败。由于还有另一个 Python 习惯用法,即更喜欢使用 try- except,因此我通常最终会放弃断言并抛出异常。我还没有找到一个适合使用断言的地方。谁能举出一些好的例子吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

两个我 2024-09-26 00:03:36

一个好的指导方针是,当触发意味着代码中存在错误时,使用assert。当您的代码假设某些内容并根据该假设执行操作时,建议使用 assert 来保护该假设。此 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.

◇流星雨 2024-09-26 00:03:36

倾向于使用断言来检查不应该发生的事情。有点像健全性检查。

另一件需要意识到的事情是,断言在优化时会被删除:

当编译时请求优化时,当前代码生成器不会为断言语句发出任何代码。

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.

乄_柒ぐ汐 2024-09-26 00:03:36

一般来说,断言是为了验证您对代码的假设,即在那个时间点,要么断言成功,要么您的实现存在某种错误。例外是实际上期望错误发生并“拥抱”它,即允许您处理它。

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.

生来就爱笑 2024-09-26 00:03:36

一个很好的例子是检查函数参数的一致性:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文