python assert 在正式产品里禁用的手法 直接-O即可
How do I disable assertions in Python?
There are multiple approaches that affect a single process, the environment, or a single line of code.
I demonstrate each.
For the whole process
Using the -O
flag (capital O) disables all assert statements in a process.
For example:
$ python -Oc "assert False"
$ python -c "assert False"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AssertionError
Note that by disable I mean it also does not execute the expression that follows it:
$ python -Oc "assert 1/0"
$ python -c "assert 1/0"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
For the environment
You can use an environment variable to set this flag as well.
This will affect every process that uses or inherits the environment.
E.g., in Windows, setting and then clearing the environment variable:
C:\>python -c "assert False"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AssertionError
C:\>SET PYTHONOPTIMIZE=TRUE
C:\>python -c "assert False"
C:\>SET PYTHONOPTIMIZE=
C:\>python -c "assert False"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AssertionError
Same in Unix (using set and unset for respective functionality)
Single point in code
You continue your question:
if an assertion fails, I don't want it to throw an AssertionError, but to keep going.
If you want the code that fails to be exercised, you can catch an assertion error:
try:
assert False, "we know this fails"
except AssertionError as e:
print(repr(e))
which prints:
AssertionError('we know this fails',)
and you'll keep going from the point you handled the AssertionError
.
References
From the assert
documentation:
An assert statement like this:
assert expression #, optional_message
Is equivalent to
if __debug__:
if not expression: raise AssertionError #(optional_message)
And,
the built-in variable
__debug__
isTrue
under normal circumstances,False
when optimization is requested (command line option-O
).
From the usage docs:
Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. See also PYTHONOPTIMIZE.
and
If this is set to a non-empty string it is equivalent to specifying the
-O
option. If set to an integer, it is equivalent to specifying-O
multiple times.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-08-26 kafka 0.11 spark 2.11 streaming例子
2017-08-26 蜜罐技术——通过布置一些作为诱饵的主机、网络服务或者信息,诱使攻击方对它们实施攻击,从而可以对攻击行为进行捕获和分析