“断言"有什么用?在 Python 中? [英] What is the use of "assert" in Python?

查看:32
本文介绍了“断言"有什么用?在 Python 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读一些源代码,并在几个地方看到了assert 的用法.

具体是什么意思?它的用途是什么?

解决方案

assert 语句几乎存在于所有编程语言中.它有助于在您的程序早期发现问题,因为它的原因很明确,而不是在其他操作失败时发现问题.

当你...

断言条件

...您告诉程序测试该条件,如果条件为假,则立即触发错误.

在 Python 中,大致相当于:

如果不是条件:引发断言错误()

在 Python shell 中尝试:

<预><代码>>>>assert True # 什么都没发生>>>断言假回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.断言错误

断言可以包含一个可选消息,您可以在运行解释器时禁用它们.

如果断言失败则打印消息:

assert False,哦不!这个断言失败了!"

不要不要像函数一样使用括号来调用assert.这是一个声明.如果您执行 assert(condition, message),您将使用 (condition, message) 元组作为第一个参数来运行 assert.

至于禁用它们,当在优化模式下运行 python 时,其中 __debug__False,断言语句将被忽略.只需传递 -O 标志:

python -O script.py

有关相关文档,请参阅此处.

I have been reading some source code and in several places I have seen the usage of assert.

What does it mean exactly? What is its usage?

解决方案

The assert statement exists in almost every programming language. It helps detect problems early in your program, where the cause is clear, rather than later when some other operation fails.

When you do...

assert condition

... you're telling the program to test that condition, and immediately trigger an error if the condition is false.

In Python, it's roughly equivalent to this:

if not condition:
    raise AssertionError()

Try it in the Python shell:

>>> assert True # nothing happens
>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

Assertions can include an optional message, and you can disable them when running the interpreter.

To print a message if the assertion fails:

assert False, "Oh no! This assertion failed!"

Do not use parenthesis to call assert like a function. It is a statement. If you do assert(condition, message) you'll be running the assert with a (condition, message) tuple as first parameter.

As for disabling them, when running python in optimized mode, where __debug__ is False, assert statements will be ignored. Just pass the -O flag:

python -O script.py

See here for the relevant documentation.

这篇关于“断言"有什么用?在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆