跳转至

一般 python 开发者都不用的冷特性——Optimize

唐彬

2023年6月22日 0:06:53

assert 语句其实在运行时可选。指定-O参数或$PYTHONOPTIMIZE环境变量时,会移除所有assertif __debug__

lie.py
print("Vulcans are incapable of lying.")

if __debug__:
    print("They just *exaggerate*.")

assert not "a lie"

python lie.py(Windows 上请py lie.py)结果如下。

Vulcans are incapable of lying.
They just *exaggerate*.
Traceback (most recent call last):
    File "lie.py", line 6, in <module>
    assert not "a lie"
AssertionError

python -O lie.py结果只有Vulcans are incapable of lying.

注意这种删除是直接把语句删了,而不是运行时再判断。你可以用 dis 模块在字节码层面验证这一点。

$ py -O -m dis lie.py
  0           0 RESUME                   0

  1           2 PUSH_NULL
              4 LOAD_NAME                0 (print)
              6 LOAD_CONST               0 ('Vulcans are incapable of lying.')
              8 PRECALL                  1
             12 CALL                     1
             22 POP_TOP

  3          24 LOAD_CONST               3 (None)
             26 RETURN_VALUE

The best Python feature you cannot use - Bite code!

$PYTHONOPTIMIZE - Command line and environment — Python 3.11 documentation

-O - Command line and environment — Python 3.11 documentation

The assert statement - Simple statements — Python 3.11 documentation

__debug__ - Built-in Constants — Python 3.11 documentation

dis — Disassembler for Python bytecode — Python 3.11.4 documentation