網(wǎng)站首頁 編程語言 正文
1. 背景
在潛意識中, assert 是應(yīng)用在unittest或pytest環(huán)境中, 不能應(yīng)用到業(yè)務(wù)代碼中, 因?yàn)閿嘌詴?dǎo)致運(yùn)行中斷,對業(yè)務(wù)有損,并且消耗內(nèi)存, 影響性能.
但不可否認(rèn), 使用斷言非常方便調(diào)試代碼
通過研讀assert的文檔, 發(fā)現(xiàn)斷言是可以被關(guān)閉的,特此記錄下
詳細(xì)的介紹參考這個文檔: 參考這篇文檔
2.解決方案
2.1 禁用assert的策略
有兩種方案
- 啟動命令行的參數(shù)中,添加-O, 也就是大寫的o
- 設(shè)置PYTHONOPTIMIZE環(huán)境變量為合適的值
2.2 禁用的原理
在python 內(nèi)部機(jī)制中, 有一常量__debug__,值為BOOL類型的, 與斷言是強(qiáng)關(guān)聯(lián)的, 因?yàn)開_debug__是常量, 所以當(dāng)python 解釋器運(yùn)行時, 不能修改它的值.
Python 3.8.13 (default, Mar 28 2022, 06:16:26)
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __debug__
True
>>> __debug__ = False
File "<stdin>", line 1
SyntaxError: cannot assign to __debug__
>>>
既然運(yùn)行時不能修改, 那沒有運(yùn)行時可以修改嗎?當(dāng)然可以的, 這取決于python 運(yùn)行模式,python運(yùn)行模式有兩種,和__debug__的關(guān)系如下表所示:
Mode | Value of debug |
---|---|
Normal (or debug)(調(diào)試模式) | True |
Optimized(優(yōu)化模式) | False |
那__debug__的值和斷言有什么關(guān)系呢?
看源碼:
if __debug__:
if not expression:
raise AssertionError(assertion_message)
所以__debug__==True時會拋出斷言異常, __debug__==False時就啥也不干,跳過了
這下清晰了
3. 實(shí)施禁用策略
3.1 啟動命令行的參數(shù)中,添加-O
驗(yàn)證方案:
1、先寫這樣一個測試腳本,命名為demo.py
# demo.py
print(f"__debug__=={__debug__}"
2、在命令行使用 禁用斷言的啟動方式
python -O demo.py
輸出結(jié)果
__debug__==False
輔助理解: 在命令行中運(yùn)行python -h,其結(jié)果也體現(xiàn)了這樣的使用方式
mac$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : remove assert and __debug__-dependent statements; add .opt-1 before
.pyc extension; also PYTHONOPTIMIZE=x
-OO : do -O changes and also discard docstrings; add .opt-2 before
.pyc extension
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-u : force the stdout and stderr streams to be unbuffered;
this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option. The following options are available:
-X faulthandler: enable faulthandler
-X showrefcount: output the total reference count and number of used
memory blocks when the program finishes or after each statement in the
interactive interpreter. This only works on debug builds
-X tracemalloc: start tracing Python memory allocations using the
tracemalloc module. By default, only the most recent frame is stored in a
traceback of a trace. Use -X tracemalloc=NFRAME to start tracing with a
traceback limit of NFRAME frames
-X showalloccount: output the total count of allocated objects for each
type when the program finishes. This only works when Python was built with
COUNT_ALLOCS defined
-X importtime: show how long each import takes. It shows module name,
cumulative time (including nested imports) and self time (excluding
nested imports). Note that its output may be broken in multi-threaded
application. Typical usage is python3 -X importtime -c 'import asyncio'
-X dev: enable CPython's "development mode", introducing additional runtime
checks which are too expensive to be enabled by default. Effect of the
developer mode:
* Add default warning filter, as -W default
* Install debug hooks on memory allocators: see the PyMem_SetupDebugHooks() C function
* Enable the faulthandler module to dump the Python traceback on a crash
* Enable asyncio debug mode
* Set the dev_mode attribute of sys.flags to True
* io.IOBase destructor logs close() exceptions
-X utf8: enable UTF-8 mode for operating system interfaces, overriding the default
locale-aware mode. -X utf8=0 explicitly disables UTF-8 mode (even when it would
otherwise activate automatically)
-X pycache_prefix=PATH: enable writing .pyc files to a parallel tree rooted at the
given directory instead of to the code tree
--check-hash-based-pycs always|default|never:
control how Python invalidates hash-based .pyc files
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>).
The default module search path uses <prefix>/lib/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONUTF8: if set to 1, enable the UTF-8 mode.
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
to seed the hashes of str and bytes objects. It can also be set to an
integer in the range [0,4294967295] to get hash values with a
predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
on Python memory allocators. Use PYTHONMALLOC=debug to install debug
hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.
PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.
5: 新的需求: 怎么在命令行中禁用斷言,看下面的對比代碼:
最關(guān)鍵是修改__debug__的值
(sse38) lzh mac$ python
Python 3.8.13 (default, Mar 28 2022, 06:16:26)
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __debug__
True
>>> exit()
(sse38) lzh mac$ python -O
Python 3.8.13 (default, Mar 28 2022, 06:16:26)
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> __debug__
False
>>>
3.2 設(shè)置PYTHONOPTIMIZE環(huán)境變量
這部分是在命令行中操作的
mac or linux 系統(tǒng)中,
(sse38) mac$ export PYTHONOPTIMIZE=0
(sse38) mac$ python demo.py
True
(sse38) mac$ export PYTHONOPTIMIZE=1
(sse38) mac$ python demo.py
False
(sse38) mac$ export PYTHONOPTIMIZE=2
(sse38) mac$ python demo.py
False
window 系統(tǒng)中,
(sse38) mac$ set PYTHONOPTIMIZE=0
(sse38) mac$ python demo.py
True
(sse38) mac$ set PYTHONOPTIMIZE=1
(sse38) mac$ python demo.py
False
(sse38) mac$ set PYTHONOPTIMIZE=2
(sse38) mac$ python demo.py
False
4 使用斷言的坑
處理或驗(yàn)證數(shù)據(jù)
處理異常和異常
運(yùn)行常有副作用的操作
原文鏈接:https://blog.csdn.net/weixin_39791387/article/details/125187612
相關(guān)推薦
- 2022-07-16 from server (NotFound): pods “XXX“ not found
- 2022-08-28 linux--network和NetManager沖突導(dǎo)致network[44649]:RTNETL
- 2022-11-07 Python根據(jù)字典值對字典進(jìn)行排序的三種方法實(shí)例_python
- 2022-11-08 Python?Pandas教程之series?上的轉(zhuǎn)換操作_python
- 2022-07-06 C#線程開發(fā)之System.Thread類詳解_C#教程
- 2022-04-24 GBase?8s數(shù)據(jù)庫主鍵約束、唯一約束和唯一索引的區(qū)別解析_數(shù)據(jù)庫其它
- 2023-03-27 詳解如何在React中優(yōu)雅的使用addEventListener_React
- 2022-06-01 idea對CPU的占用率過大問題的解決方法_相關(guān)技巧
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支