Python‘s Assert Syntax

简介: Python‘s Assert Syntax

Python’s Assert Syntax
It’s always a good idea to study up on how a language feature is actually implemented in Python before you start using it. So let’s take a quick look at the syntax for the assert statement, according to the Python docs:

assert_stmt :: = "assert" expression1 ["," expression2]

In this case, expression1 is the condition we test, and the optional expression2 is an error message that’s displayed if the assertion fails.At execution time, the Python interpreter transforms each assert statement into roughly the following sequence of statements:

if __debug__:
        if not expression1:
            raise AssertionError(expression2)

Two interesting things about this code snippet:

Before the assert condition is checked, there’s an additional check for the debug global variable. It’s a built-in boolean flag that’s true under normal circumstances and false if optimizations are requested.We’ll talk some more about that later in the “common pitfalls” section.

Also, you can use expression2 to pass an optional error message that will be displayed with the AssertionError in the traceback. This can simplify debugging even further. For example, I’ve seen code like this:

>>> if cond == 'x':
...     do_x()
... elif cond == 'y':
...     do_y()
... else:
...     assert False, (
...             'This should never happen, but it does '
...             'occasionally. We are currently trying to  '
...             'figure out why. Email dbader if you '
...             'encounter this in the wild. Thanks!')

Is this ugly?Well, yes. But it’s definitely a valid and helpful technique if you’re faced with a Heisenbug in one of your applications.

Notification:

Wikipedia:Heisenbug

相关文章
|
Python
Python assert断言语句
Python assert断言语句
86 0
|
3月前
|
SQL 数据库 Python
【Python】已完美解决:(156, b“Incorrect syntax near the keyword ‘group’.DB-Lib error message 20018, severity
【Python】已完美解决:(156, b“Incorrect syntax near the keyword ‘group’.DB-Lib error message 20018, severity
74 0
|
3月前
|
文字识别 Python
python -m pip ,SyntaxError: invalid syntax,下载需要pip的包
python -m pip ,SyntaxError: invalid syntax,下载需要pip的包
|
3月前
|
Python
【Python】已解决:(Python最新xlrd库读取xlsx报错)SyntaxError: invalid syntax
【Python】已解决:(Python最新xlrd库读取xlsx报错)SyntaxError: invalid syntax
64 0
|
3月前
|
SQL 关系型数据库 MySQL
【Python】已解决:ERROR 1064 (42000): You have an error in your SQL syntax. check the manual that correspo
【Python】已解决:ERROR 1064 (42000): You have an error in your SQL syntax. check the manual that correspo
467 0
|
5月前
|
IDE 搜索推荐 开发工具
|
5月前
|
测试技术 Python
|
JSON 数据格式 Python
python中的语法使用(easydict set() plt.subplots() assert)
目录 1 easydict的使用 2. 集合(set) 3 plt.subplots()使用 3.1 方法1 3.2 方法2 4. assert断言
155 0
python中的语法使用(easydict set() plt.subplots() assert)
|
Python
Python assert的用法
Python assert的用法
97 0
Python assert的用法
|
Python
Python 的 assert关键字
Python 的 assert关键字
276 0
Python 的 assert关键字