栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python‘s Assert Syntax

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853774.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号