首页 > 编程笔记

Python __debug__内置变量的用法

Python 解释器有一个内置变量 __debug__,__debug__ 在正常情况下的值是 True。

print(__debug__)

输出结果如下:
True

当用户以最佳化模式启动 Python 解释器时,__debug__ 值为 False。要使用最佳化模式启动 Python 解释器,需要设置 Python 命令行选项-O,代码如下:
C:\Users\Administrator>python -O
Python 3.10.1 (tags/v3.10.1:2cd268a, Dec  6 2021, 19:10:37) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>__debug__
False
用户不可以设置 __debug__ 变量的值,下面的示例将 __debug__ 变量设成 False,结果产生错误。
>>>__debug__ = False
  File "<stdin>", line 1
SyntaxError: cannot assign to __debug__
__debug__ 变量也可以用来调试程序,下面的语法与 assert 语句的功能相同。
If __debug__:
    If not (<测试码>):
        raise AssertionError [, 参数]
下面的示例检测函数的参数类型是否是字符串。如果函数的参数类型不是字符串,就输出一个 AssertionError 异常。
import types
def checkType(arg):
    if __debug__:
        if not (type(arg) == str):
            raise AssertionError('参数类型不是字符串')
checkType(10)
输出异常信息如下:
raise AssertionError('参数类型不是字符串')
AssertionError: 参数类型不是字符串

推荐阅读